問題是這樣的:
兩個人玩撿樹枝游戲,樹枝的數量由用戶來輸入。但是樹枝的數量不能超過21,用投擲硬幣來決定先後順序。每個人能一次性拿一枝或者兩枝。誰拿到最後一枝樹枝誰就輸。
請用C++寫出來。
#include <time.h>
#include <iostream>
using namespace std;
int main()
{
char player[2][40];
int num,loop,loops,branch,start,branchTotal;
int winCount[2]={0,0};
cout<<"-------------樹枝游戲---------------\n";
cout<<"請輸入第一名玩家姓名:";
cin>>player[0];
cout<<"請輸入第二名玩家姓名:";
cin>>player[1];
do
{
cout<<"請輸入局數(不超過5局):";
cin>>loop;
} while (loop>5 || loop<1);
do
{
cout<<"請輸入每局樹枝總數(不超過21枝)";
cin>>branchTotal;
} while (branchTotal>21 || branchTotal<1);
loops=1;
while(loops<=loop)
{
srand( (unsigned)time( NULL ) ); //根據時間生成隨機數種子
start = rand()%2;//隨機產生誰先開始
cout<<"\n\n<游戲第"<<loops<<"局開始,每次只能拿走1-2個樹枝>\n";
branch=branchTotal;
while(branch>0)
{
cout<<"當前樹枝總數:"<<branch<<" ";
do
{
cout<<"請"<<player[start]<<"取樹枝:";
cin>>num;
} while ( num<1 || num>2 );
branch-=num;
if(branch<=0)
{
cout<<player[start]<<"本局獲勝!\n";
winCount[start]++;
break;
}
start=(start+1)%2;
}
loops++;
}
cout<<"--------游戲結束-----------\n";
cout<<loop<<"局,"<<player[0]<<"勝"<<winCount[0]<<"局; "<<player[1]<<"勝"<<winCount[1]<<"局\n\n";
if( winCount[0] > winCount[1])
{
cout<<"恭喜!最終"<<player[0]<<"獲勝!\n";
}
else if( winCount[0] < winCount[1])
{
cout<<"恭喜!最終"<<player[1]<<"獲勝!\n";
}else
{
cout<<"平局!\n";
}
return 0;
}