我一直在c++论坛上浏览一个非常有用的程序列表:
http://www.cplusplus.com/forum/articles/12974/我现在正在执行第三个程序,叫做while(user==gullible)。论坛说我应该学习如何使用for, while, do-while循环用于这个特定的程序,它让用户输入除尝试数以外的任何数字(因此,如果尝试数为1,程序将输出"输入除1以外的任何数字:")。如果用户输入尝试数,我可以让程序结束,但我希望程序在尝试10次后结束,这就是我遇到的问题。到目前为止,我的程序如下:
int main()
{
int numberOfAttempts = 0;
int userGuess;
cout << "Enter any number other than " << numberOfAttempts << ": ";
cin >> userGuess;
while (userGuess != numberOfAttempts)
{
numberOfAttempts += 1;
cout << "Enter any number other than " << numberOfAttempts << ": ";
cin >> userGuess;
}
if (userGuess == numberOfAttempts)
{
cout << "Hey! I told you to enter any number other than " << numberOfAttempts << "!";
return 0;
}
if (numberOfAttempts == 10)
{
cout << "Wow! You're a hell of a lot more patient than me! You win.";
return 0;
}
}
我遇到了一个问题,程序完全忽略了最后一个"if"语句。我不是在找人解决我的问题,我只是需要一点指导。除了"while"one_answers"if"语句之外,我应该使用什么(如果我应该使用的话)?
提前感谢!
您的if
语句在您的循环之外:
while (userGuess != numberOfAttempts)
{
numberOfAttempts += 1;
cout << "Enter any number other than " << numberOfAttempts << ": ";
cin >> userGuess;
if (userGuess == numberOfAttempts)
{
cout << "Hey! I told you to enter any number other than " << numberOfAttempts << "!";
return 0;
}
if (numberOfAttempts == 10)
{
cout << "Wow! You're a hell of a lot more patient than me! You win.";
return 0;
}
}
这就是你要找的。至于你的评论:你可以在两者之间放置任意多的作用域。如果你想让你的if
在每个循环中执行,当然你必须把它包括在循环括号内。
如果您希望运行最多10次,则必须将以下if
条件置于while
循环中,并输入值10作为userGuess
if (numberOfAttempts == 10)
{
cout << "Wow! You're a hell of a lot more patient than me! You win.";
return 0;
}