我已经在C ++论坛上创建了一个非常有用的程序列表:
http://www.cplusplus.com/forum/articles/12974/
我目前正在使用第三个名为while(user == gullible)的程序。论坛上说我应该学习如何使用for,while,do-while循环来实现这个特定程序,输入除尝试次数以外的任何数字(因此,如果尝试次数为1,程序将输出"输入除1以外的任何数字:")。如果用户输入尝试号码,我可以让程序结束,但我希望程序以十次尝试结束,这是我遇到的问题。到目前为止,我的计划如下:
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;
}
}
我遇到的问题是程序完全忽略了最后一个&#34; if&#34;声明。我不是在找人来解决我的问题,我只需要一点指导。我应该使用什么(如果我应该的话)而不是&#34;而&#34;和&#34;如果&#34;声明?
提前致谢!
答案 0 :(得分:1)
您的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
,当然您必须将它包含在循环括号中。
答案 1 :(得分:1)
如果您希望最多运行10次并且输入值10为if
while
循环中放置以下userGuess
条件
if (numberOfAttempts == 10)
{
cout << "Wow! You're a hell of a lot more patient than me! You win.";
return 0;
}