while (weather != 'S' || 'R' || 'W') {
cout << "Invalid input for weather" << endl;
std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
cin >> weather;
}
如果weather等于S R或W,我希望它继续执行程序,但如果不是S R或W,那么我希望它运行while语句。但是,即使天气输入是SR或W,它也会运行while语句。有什么建议吗?
我试过
while ((weather != 'S') || (weather != 'R') || (weather != 'W')) {
cout << "Invalid input for weather" << endl;
std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
cin >> weather;
}
但这也没用。我甚至尝试过
while (weather != 'S') {
while (weather != 'R') {
while (weather != 'W')) {
cout << "Invalid input for weather" << endl;
std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
cin >> weather;
}
}
}
但似乎什么都不管用。
如果所有条件都为true,则需要执行while循环,这意味着&&
而不是||
while ((weather != 'S') && (weather != 'R') && (weather != 'W')) {
试着大声说"如果天气不等于S,天气不等于R,天气不相等W,就执行循环"。
另一种写入相同条件的方法是
while (!((weather == 'S') || (weather == 'R') || (weather == 'W'))) {
试着大声说"如果不是天气等于S、天气等于R或天气等于W,就执行循环"。
对于初学者来说,在涉及否定的地方犯逻辑错误是很常见的。也许你混淆了上面的两种可能性,并得出了一个不等于它们中任何一种的表达式。