为什么我的while while循环永远不会结束? C++
问题描述:
int main()
{
int wordCode;
const int QUIT_MENU = 9;
菜单为什么我的while while循环永远不会结束? C++
do
{
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___.\n" << endl;
cout << "Input a 1 if you want the sentence to be finished with party." << endl;
cout << "Input any other number for the word country.\n" << endl;
cout << "Please input your choice now." << endl;
cin >> wordCode;
cout << endl;
writeProverb(wordCode);
while (wordCode >= 1 || wordCode <= 2)
{
cout << "You have not entered a valid selection." << endl;
cout << "Please eneter a 1 or a 2." << endl;
}
if (wordCode != QUIT_MENU)
{
switch (wordCode)
{
case 1:
writeProverb(wordCode);
break;
case 2:
writeProverb(wordCode);
}
}
是退出这个循环的正确方法?
}while (wordCode != QUIT_MENU);
return 0;
}
开始写谚语的void函数。
void writeProverb (int wordCode)
{
//Fill in the body of the function to accomplish what is described above
if (wordCode == 1)
{
cout << "Now is the time for all good men to come to the aid of their party." << endl;
}
if (wordCode == 2)
{
cout << "Now is the time for all good men to come to aid the aid of their country." << endl;
}
}
“您尚未输入有效的选择。” “请注入1或2”。
无论选择什么值,上述文本都会重复。
答
为什么要这样呢?
while (wordCode >= 1 || wordCode <= 2)
用户输入:
wordCode >= 1 wordCode <= 2
1 True True -> True || True -> True
-1 False True -> False || True -> True
2 True True -> True || True -> True
3 True False -> True || False -> True
999999 True False -> True || False -> True
-99999 False True -> False || True -> True
无论用户输入什么号码,病情可以从字面上永远不会成为虚假。
答
变化
while (wordCode >= 1 || wordCode <= 2)
到
if (wordCode == 1 || wordCode == 2)
你不想要的那部分循环;外层do/while
处理就好了。你只需要输出一次消息。
答
为了增加马克B的答案,我想你想while (wordCode == 1 || wordCode == 2)
答
更改 “而(wordCode> = 1 || wordCode < = 2)” 至“,而(wordCode> = 1 & & wordCode < = 2 )”。这应该可以解决你的问题。
这与'if(true)' – 2014-10-07 21:38:39
糟糕有何不同。接得好 – 2014-10-07 23:05:48