[英]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.