打印每一卷的得失

时间:2018-11-11 02:50:23

标签: c++ arrays

我现在正在学习C ++,我对如何使用它有点困惑。我正在对赌博游戏CRAPS进行编程,我希望输出像在第一轮,第二轮等中获胜的游戏数量一样

____ games won and ____ games lost on roll 
____ games won and ____ games lost on roll 

我只是迷失了如何获得每项胜利的数,而在每次掷骰后却输了。

我尝试在每次掷骰子时都包含数组,但它表示存在以下错误:

invalid types 'int[int]' for array subscript
++wins[roll];

我不明白错误的含义。有人可以帮助新手吗?只需要一些提示:)

到目前为止,这是我的代码,我认为我需要更改:

unsigned int rollDice();
int wins;
int loses;
int winSum = 0;
int loseSum = 0;
int roll;

int main(){
  enum class Status {CONTINUE, WON, LOST};
  srand(static_cast<unsigned int>(time(0)));

  unsigned int myPoint{0};
  Status gameStatus;
  unsigned int sumOfDice{rollDice()};

  for (int i = 1; i <=1000; i++){
    sumOfDice = rollDice();
    roll = 1;

    while(Status::CONTINUE == gameStatus){
      sumOfDice = rollDice();
      ++roll;

      if (sumOfDice == myPoint){
        gameStatus = Status::WON;
      }else if(sumOfDice == 7){
        gameStatus = Status::LOST;
      }
    }

    if(roll > 21){
      roll = 21;
    }

    if (Status::WON == gameStatus){
      ++wins[roll]; //maybe has smt to do w this one
      winSum++;
    }else{
      ++loses[roll]; //maybe has smt to do w this one
      loseSum++;
    }
  }
  int totalGame = winSum + loseSum;
  int length = 0;

  for (int i = 1; i <= 21; i++){
    if(i == 21){
      cout << wins[i] << " games won and " << loses[i]
         << " games lost on rolls after 20th roll" << endl;
         //maybe has smt to do w this one
    }else{
      cout << wins[i] << " games won and " << loses[i]
         << " games lost on roll " << i <<endl;
         //maybe has smt to do w this one
    }
  }
  cout << winSum << "\n"<<endl;
  cout << loseSum;

}

unsigned int rollDice() {
  int die1{1 + rand()%6};
  int die2{1 + rand()%6};
  int sum{die1+die2};

  return sum;
}

再来一次,帮忙!

1 个答案:

答案 0 :(得分:0)

请务必密切注意您的类型。

您已在第2行和第3行将变量winsloses声明为类型int,但是您尝试像在{{1} }和++wins[roll]。因此,您确实可以正确确定问题所在的线路,而不是问题所在。

您将必须将++loses[roll]wins的声明更改为一个数组,但还要更改一个足够大以容纳骰子掷骰所有可能值的数组。由于掷骰子的最大值为12,因此您应按以下方式声明loseswins

loses

之所以为13而不是12的原因是因为数组从0开始,所以如果您希望能够将int存储在位置12,则数组的长度必须为13个元素(0-12)。