閱讀435 返回首頁    go 阿裏雲 go 技術社區[雲棲]


輪流拾取火柴問題

#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 man
	while (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;
}

最後更新:2017-04-02 15:15:31

  上一篇:go 工信部或將召集國內各大搜索引擎
  下一篇:go 1到n的全排列