c++ - 带外循环的内循环迭代
问题描述
我有一个简单的嵌套 while 循环情况,但我不确定如何在第二个循环内增加 numGuesses 以在第一个循环不再小于 5 时转义它。
while(numGuesses<5){
while(!correct){
cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
numGuesses++;
cin >> guess;
if(guess<number){
cin.clear(); //clears input stream
cin.ignore(256, '\n');
cout << "\nSorry, your guess is too low";
}
else if (guess>number){
cout << "\nSorry, your guess is too high";
}
else{
cout << "\nYou guessed right, you win!";
correct = !correct;
}
}
}
cout << "Sorry, you lost. The number is: " << number;
每次内部 while 循环迭代时,我都希望 numGuesses 增加,但我猜它不在其范围内?对不起菜鸟问题。完整代码:https ://ctxt.io/2/AAAgfdIGEg
解决方案
你应该只使用一个while循环!毕竟,您循环播放的内容是在提示您进行猜测。不需要在其中进行第二层循环。想一想您何时不想再要求猜测——当猜测达到 5 或当他们猜对时。那么你什么时候想继续要求猜测呢?当猜测数少于 5 且他们没有猜对时。另外,您想根据correct
.
while(numGuesses<5 && !correct) {
cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
numGuesses++;
cin >> guess;
if(guess<number){
cin.clear(); //clears input stream
cin.ignore(256, '\n');
cout << "\nSorry, your guess is too low";
}
else if (guess>number){
cout << "\nSorry, your guess is too high";
}
else{
cout << "\nYou guessed right, you win!";
correct = !correct;
}
}
if (!correct) { // loop stopped before they got it correct
cout << "Sorry, you lost. The number is: " << number;
}
您还需要"\n"
s 或std::endl
s 在打印语句的末尾,否则您的代码将在一行上打印所有内容。
推荐阅读
- obfuscation - 有哪些好的/便宜的数据混淆和数据屏蔽工具?
- angular8 - 在 Angular 8 中设置启动页面/组件但出现错误“Angular CLI 进程未开始侦听请求”
- android - Java.Lang.RuntimeException:Firestore (0.6.6-dev) 中的内部错误,无法在我的应用程序和 Firestore 项目之间连接
- hsqldb - 将序列值设置为 HSQL 中列的默认值
- kotlin - Kotlin 中算术表达式中的整数转换
- c++ - 在 OpenGL 中绘制单色二维数组
- python - Networkx中的最小有向生成树
- sql - 跨多行匹配列值
- database-design - 处理五星级评级系统的最佳方式?
- python - 有没有一种方便的方法可以使用 cvxpy 来表达 MIP 的连续松弛?