如果用户对C++说,如何提前结束循环
How to end a loop early if a user says to C++
注意:这是一项家庭作业。
我正在试着制作一个玩"猪"游戏的程序!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"语句(根据大小写适当的值)在循环中怎么样?这将中断循环和函数,但返回所需的值。
- 为什么在这个代码结束循环中没有得到结束
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 试图对缓存进行跨步测试,但程序并没有结束
- Python中的for循环与C++有何不同
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 删除映射和分割错误中的一个过去结束元素
- 在C++中释放内存期间,迭代器与指针有何不同
- 如何使用 SFML 在贪吃蛇游戏中定义游戏结束?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- 在函数结束后使用指向变量的指针是否安全?
- C ++尝试并捕获未结束的程序
- 为什么我的程序在输入某个形状的面积的测量值后没有结束?
- 取消引用结束指针到数组类型的一个
- 基本C++计划提前结束
- 虽然循环总是提前结束一个循环
- 如果用户对C++说,如何提前结束循环
- While循环提前结束
- 如何不间断地提前结束一个循环