想知道我的代码有什么问题?一旦播放器名称达到 100,应该输出获胜者,但在之后再次循环

Wondering what's wrong with my code? Should output winner once it playerName reaches 100 but loops again after

本文关键字:输出 获胜者 循环 之后 什么 问题 代码 我的 播放器 想知道      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int PLAYER1 = 0;
const int PLAYER2 = 1;
const int WINNING_SCORE = 100;
void printIntro(){
cout << "Welcome to the dice game Pig!" << endl;
cout << "The objective is to be first to score 100 points." << endl;
cout << endl;
return;
}
int humanTurn(string playerName, int playerScore){
    char userInput = 'a';
int playerOrg = playerScore;
do{
int roll = (rand()%6)+1;
if(roll ==1){
   cout << playerName << endl;
   cout << "You rolled a 1" << " (PIG!)" << endl;
   cout << "Your turn is over" << endl;
   cout << "Your score: " << playerOrg << endl;
   cout << endl;
   userInput = 'n';
 }

 else  if (roll != 1){
 cout << playerName << endl;
 cout << "You rolled a " << roll << endl;
 playerScore = roll + playerScore;
 cout << "Your score: " << playerScore << endl;
 if (playerScore <100){
    cout << "Do you want to roll again? " << "(y/n): ";
    cin >> userInput; 
    cout << endl;
 }
 } else {
    userInput = 'n';
 }

} while (userInput == 'y');
return playerScore;

}

int main() {
srand(4444);
// setup and initialize variables
int turn = PLAYER1;
int player1score = 0;
int player2score = 0;
string player1name;
string player2name;
printIntro();
cout << "Player 1 - Enter your name: "<< endl;
cin >> player1name;
cout << "Player 2 - Enter your name: "<< endl;
cin >> player2name;

//play game
while (player1score < WINNING_SCORE && player2score < WINNING_SCORE) {
    //player 1's turn or player 2's turn
    if (turn == PLAYER1) {
        player1score = humanTurn(player1name, player1score);
    }
    else {
        player2score = humanTurn(player2name, player2score);
    }
    if (turn == PLAYER1){
        turn = PLAYER2; 
    }
    else if (turn == PLAYER2){
        turn = PLAYER1;
    }
  }
  if (player1score >=100){ 
    cout << endl;
    cout << player1name << " Wins!" << endl;
  }
  else if (player2score >=100){
    cout << endl;
    cout << player2name << " Wins!" << endl;
 }

 return 0;
 }

查尔斯你掷出的是4你的分数:97你想再滚一次吗?(y/n):查尔斯你掷出的是2你的分数:99分你想再滚一次吗?(y/n):查尔斯你掷出的是6你的分数:105分查尔斯你掷出一个1(猪!)轮到你了你的得分:36

查尔斯获胜!

当我修复代码缩进时,如下:

    if (roll == 1)
    {
        ...
    }
    else if (roll != 1)
    {
        ...
        if (playerScore < 100)
        {
            ...
        }
    }
    else
    {
        set exit condition
    }

变得明显。if (roll == 1)else if (roll != 1)消除了else的可能性。但是如果您将else向上移动一行,您将得到:

    if (roll == 1)
    {
        ...
    }
    else if (roll != 1)
    {
        ...
        if (playerScore < 100)
        {
            ...
        }
        else
        {
            set exit condition
        }
    }

现在它将按预期退出。

快餐:

正确缩进代码

熟悉开发环境附带的调试器。即使没有固定缩进,它也会使发现这个完全微不足道。