You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中逻辑或(||)运算符不符合预期问题排查

C++输入判断逻辑错误的问题解决

你的问题出在if条件的逻辑运算符使用错误,ans != 'y' || ans != 'n'这个表达式永远为真,不管你输入'y'还是'n':

  • 输入'y'时,ans != 'n'是真,逻辑或(||)只要一个为真就整体为真,所以触发"wrong";
  • 输入'n'时,ans != 'y'是真,同样触发"wrong"。

正确的逻辑应该是判断输入既不是'y'也不是'n',这时候要用逻辑与(&&),把条件改成:

if(ans != 'y' && ans != 'n')

修正后的完整代码:

#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 << "wrong\n";
        }
        else
        {
            correct = false;
        }
    }
    
    cout << "Thanks for your input!" << endl;
    
    return 0;
}

这样就能正常识别'y'和'n',只有输入其他字符时才会提示错误。

内容的提问来源于stack exchange,提问作者David Garza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:50:38