我有一个简单的嵌套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
答案 0 :(得分:2)
您应该只使用一个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"
或std::endl
,否则代码会将所有内容打印在一行上。
答案 1 :(得分:1)
您不需要2个小时...
while(numGuesses < 5 && !correct)
{
// your logic here
}
之后,您可以检查变量正确或 numGuesss 。例如:
if(!correct)
// your code