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

字符相等运算符失效:字符串回文判断中if条件始终为false

字符相等判断失效的问题解决

核心问题出在运算符优先级上:not(逻辑非)的优先级低于相等运算符==,你写的not line[i] == line[line.size() - i - 1]会被编译器解析为(not line[i]) == line[line.size() - i - 1],这完全不是你想要的“两个字符不相等”的判断逻辑。

举个例子,当line[i]是'h'(ASCII值非0),not 'h'会被转为布尔值false,然后判断false == 'd'('d'转为布尔值是true),结果自然是false,所以你的if条件永远不会触发。

两种修正方案

  1. 用括号强制改变运算顺序:
for (size_t i = 0;i * 2 < line.size(); ++i){
    cout << line[i] << " == " << line[line.size() - i - 1] << endl;
    if (not (line[i] == line[line.size() - i - 1])){
        palindrome = false;
        cout << "False" << endl;
        break;
    }
}
  1. 直接使用不等运算符!=(更推荐,可读性更高):
for (size_t i = 0;i * 2 < line.size(); ++i){
    cout << line[i] << " == " << line[line.size() - i - 1] << endl;
    if (line[i] != line[line.size() - i - 1]){
        palindrome = false;
        cout << "False" << endl;
        break;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:58:27