想知道我的代码有什么问题?一旦playerName达到100就应该输出胜利者,但之后再循环

时间:2016-11-10 00:54:54

标签: c++

#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

Charles Wins!

1 个答案:

答案 0 :(得分:0)

当我修复代码缩进时,这个:

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

现在它将按预期退出。

外卖:

正确缩进代码。

熟悉the debugger that came with your development environment.即使缩进没有修复,也会发现这完全无关紧要。