卡住了一个c++的幸运七游戏程序
Stuck on a c++ lucky seven game program
My Basic Algorithm:
询问投入金额;掷两个六面骰子;如果它们加起来是7,在钱数上加4;否则,从金额中减去1;循环至moneyamount<0
;循环游戏用户在提示再次游戏时说n。
/*
*File: hw3
*Author: Nathaniel Goodhue
*
*Created on: 9/15/15
*Description: Game of lucky sevens
*
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
srand (time(NULL));
double moneyAmount;
int winValue = 7;
int numRolls = 0;
char playAgain = 'y';
while(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
while(moneyAmount>0)
{
int roll1= (rand()%6)+1;
int roll2 = (rand()%6)+1;
if(roll1+roll2 == winValue)
{
moneyAmount+=4;
numRolls++;
}
else
{
moneyAmount-=1;
numRolls++;
}
}
cout<<"It took "<<numRolls<<" roll(s) to lose all of your money"<<endl;
// cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
cout<<"Play again? y/n"<<endl;
cin>>playAgain;
if(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
numRolls = 0;
}
else
{
break;
}
}
return 0;
}
以上是我当前的代码。它按预期工作。我所坚持的是,我需要能够在钱降到0以下后立即实现这行代码:
cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
我需要知道什么时候有最多的钱,在多少次滚动之后出现。maxAmount
变量是达到的最大金额,maxRolls
变量是达到maxAmount
时的滚动次数。
添加到代码中非常简单。你能做的就是检查他们拥有的钱是否大于最大的钱。如果是,则将max设置为当前值,并记录获得该值所需的转数。
int maxAmount = moneyAmount, maxRolls = 0;
while(moneyAmount > 0)
{
int roll1 = (rand() % 6) + 1;
int roll2 = (rand() % 6) + 1;
numRolls++;
if(roll1 + roll2 == winValue)
moneyAmount += 4;
else
moneyAmount -= 1;
if (moneyAmount > maxAmount)
{
// the current amount of money is greater than the max so set max to current and get the number of rolls
maxAmount = moneyAmount;
maxRolls = numRolls;
}
}