坚持c ++幸运七游戏计划

时间:2015-09-17 17:27:24

标签: c++ dice

我的基本算法:

要求输入金额;滚动两个6面骰子;如果他们加起来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时的滚动数。

1 个答案:

答案 0 :(得分:2)

添加到代码中非常简单。您可以做的是检查他们所拥有的金额是否大于最大金额。如果是,则将max设置为current并记录获得该值所需的转数。

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;
    }
}