或者操作员没有按应有的方式操作?c++



我根本不明白错误是什么。一旦我让if语句包含or运算符,我的程序就不会接受任何正确的输入。相反,即使我输入yn,它也会一直输出错误。

(如果这很简单,也很抱歉,我是编程新手(

我尝试使用else if,但它仍然不适用于我。

#include <iostream>
using namespace std;
int main()
{    
char ans;
bool correct = true;

while(correct){
cout << "Do you like ice cream? (y/n) ";
cin >> ans;
if(ans != 'y' || ans != 'n')
{
cout << "wrongn";
}
else
{
correct = false;
}
}

cout << "Thanks for your input!" << endl;

return 0;
}
if(ans != 'y' || ans != 'n')

此值的计算结果始终为True。你应该使用&amp;在这种情况下,而不是||。

试着在你的脑海中模拟:

ans='n'将第一部分评估为True

ans='y'将评估第二部分为True

ans="马铃薯"将评估两个部分的真实

最新更新