[英]conditional statement in while loop
我肯定錯過了什么。 我正在做一個學習c ++的練習,它要求用戶輸入c,p,t或g字符然后繼續進行,否則重新請求提示符,所以我這樣寫:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main(void){
cout << "Please enter one of the following choices:" << endl;
cout << "c) carnivore\t\t\tp) pianist\n";
cout << "t) tree\t\t\t\tg) game\n";
char ch;
do{
cout << "Please enter a c, p, t, or g: ";
cin >> ch;
cout << "\"" << ch << "\"" << endl;
}while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');
cout << "End" << endl;
cin.clear();
cin.ignore();
cin.get();
return 0;
}
這是行不通的,即使按了兩個正確的字符之一,我得到的只是提示重新請求它。
但是,如果我更改此行:
while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');
至
while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');
這是為什么? 我的理解是,“ OR”語句應在其中一項測試正確的情況下起作用。
這是為什么? 我的理解是,“ OR”語句應在其中一項測試正確的情況下起作用。
究竟。 總有一項測試通過。 字符不是'c'
或'p'
。 不能同時是'c'
和'p'
。 因此,條件始終為真,從而導致無限循環。
帶有連接詞的替代條件之所以起作用,是因為ch
等於替代之一時它就為假:不等式之一為假,因此整個條件為假。
我的理解是,“ OR”語句應在其中一項測試正確的情況下起作用。
好吧,您可以使用||
,但表達式必須為:
while(!(ch == 'c' || ch == 'p' || ch == 't' || ch == 'g'));
通過應用德摩根定律 ,以上簡化為:
while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.