轮流拾取火柴问题

来源:互联网 发布:淘宝代运营怎么收费 编辑:程序博客网 时间:2024/04/28 07:34
#include <iostream>using namespace std;///////////////////////////////////////////////////////////////////////////////////现有21根火柴,两人轮流取,每人每次可取走1-4根,不可多取,也不能不取,谁取最后////一根火柴则谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;计算机一 ////方为“常胜将军”。                                                           ///////////////////////////////////////////////////////////////////////////////////int main(){int nSticks = 21;int nManTaken = 0;int nMerchineTaken = 0;cout << ">> ----------------------- Game Begin ------------------" << endl;nSticks -= 1;  //the last stick must be taken by manwhile (nSticks){cout << "How many stick do you wish to take(1~4)?";do {  //保证输入的数是合法的cin >> nManTaken;if (nManTaken >4 || nManTaken < 1){cout << "input 1~4 : "; }} while (nManTaken >4 || nManTaken < 1);nSticks -= nManTaken;cout << (nSticks + 1) << " stick left in the pile." << endl;if (nSticks >= 5){nMerchineTaken = 1;}else {switch (nSticks){case 1:nMerchineTaken = 1;break;case 2:nMerchineTaken = 2;break;case 3:nMerchineTaken = 3;break;case 4:nMerchineTaken = 4;break;}}nSticks -= nMerchineTaken;cout << "compute take " << nMerchineTaken << " stick." << endl;if (nSticks > 0){cout << (nSticks + 1) << " stick left in the pile." << endl;}else {cout << " 1 stick left in the pile." << endl;cout << "How many stick do you wish to take(1~1)?";do {  //保证输入的数是合法的cin >> nManTaken;} while (nManTaken != 1);cout << " You have taken the last stick." << endl;cout << " * * * You lose!" << endl;}}cout << ">> ----------------------- Game Over ------------------" << endl;return 0;}