如果用户对C++说,如何提前结束循环

How to end a loop early if a user says to C++

本文关键字:何提前 结束 循环 用户 C++ 如果      更新时间:2023-10-16

注意:这是一项家庭作业。

我正在试着制作一个玩"猪"游戏的程序!Pig是一个有以下规则的游戏:

1. First to get 100 GAME POINTS is the victor. 2. On your turn, you roll a dice. If you get a 1 at any roll, you end your turn and add 0 to your GAME SCORE. 3. If you roll any value other than a 1, you have the option to HOLD or PLAY. If you PLAY, your roll is added to your TURN SCORE and you roll again. If you HOLD, your TURN SCORE is added to your GAME SCORE and the turn passes to the computer.

游戏进行得很容易,直到我遇到以下问题(见代码):

int player(){
    char PlayAgain = 'Y';
    int turn_score = 0;
    while (PlayAgain != 'N' || PlayAgain != 'n'){
        int dice;
        srand(time(NULL));
        dice = rand() % 6 + 1;
        turn_score = turn_score + dice;
        if (dice != 1){
            cout << "You rolled a " << dice << "! Would you like to roll again? [Y/N]: ";
            cin >> PlayAgain;
            if (PlayAgain == 'N' || PlayAgain == 'n'){
                /*END TURN AND return turn_score;*/
            }
        }
        if (dice == 1){
            cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.n";
            system("PAUSE");
            /*END TURN, NO SCORE ADDED*/
        }
    }
}

我如何让程序提前结束循环(如果游戏保持或骰子==1)并返回正确的值(如果保持,则返回turn_score。否则返回0)?[参见两个注释部分]

您可以使用break来退出循环。既然你说你想返回"正确的值",那么你应该这样做:

关于第一个if子句

if (PlayAgain == 'N' || PlayAgain == 'n'){
            /**Game-Specific logic here**/
            return turn_score
        }

第二个:

if (dice == 1){
        cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.n";
        /**Game-Specific logic here**/
        cin.get();
        return turn_score;
    }

返回语句不需要在函数的末尾,并且多个返回语句可以共存于同一函数

与其更正您的代码,不如让您清楚地了解这里实际需要什么。


听说过break;的声明。让我们通过一个简单的例子来理解请参阅下面的代码片段,您的程序从用户那里获取输入,它一直从用户那里获得输入,直到您按下"A"

char var;
while(true)
{
cin>>var;
if(var=='A') break;
}

现在,在这个程序中,while循环被设置为true,并将继续运行并接受用户的输入,而if语句在用户输入"A"之前不会运行。当"A"作为输入时,break将为您从while循环中获得控制权。

让您的"return"语句(根据大小写适当的值)在循环中怎么样?这将中断循环和函数,但返回所需的值。