[英]C++ Why does my do-while loop fail to end as soon as boolean condition is met?
[英]Why does my do while loop never end? C++
int main ()
{
int wordCode;
const int QUIT_MENU = 9;
菜单
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设为Eneter。”
无论选择什么值,以上文本都会重复。
为什么要这样
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)
将“ while(wordCode> = 1 || wordCode <= 2)”更改为“ while(wordCode> = 1 && wordCode <= 2)”。 那应该解决您的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.