c++ - C++无法弄清楚为什么它会给出误报(newbie)

标签 c++ if-statement boolean-expression logical-or

嘿,所以我最近开始学习C++,我不知道为什么这个问题总是会给人带来错误的肯定。

也许有人可以帮忙?

// [Included stuff]

using namespace std;

int main() {

    int erg = 5;
    int inp;

    cout << "Answer: 3 + 2: "; 
    cin >> inp;

    if (inp == erg) {
        cout << "True!";
    };

    if (inp <= erg || inp >= erg) {
        cout << "False!";
    }
    else {

    };
}

Image of the Executed Code

最佳答案

该if语句中的条件

if (inp <= erg || inp >= erg) {
    cout << "False!";
}

表示inp可以等于任何数字。这是条件始终为true的条件,因此附上的语句
    cout << "False!";

输出。

看来你的意思是
if (inp != erg) {
    cout << "False!";
}

或(这太令人困惑了,因为太复杂了)
if (inp < erg || inp > erg) {
    cout << "False!";
}

或者你可以写类似
if (inp == erg) {
    cout << "True!\n";
}
else if ( inp < erg ) {
    cout << "False! Less than the result\n";
}
else {
    cout << "False! Greater than the result\n";
}

如果你有这样的情况
inp == erg

那么它的否定看起来像
!( inp == erg )

或更可读
not ( inp == erg )

那和
inp != erg

写就足够了
if (inp == erg) {
    cout << "True!\n";
}
else {
    cout << "False!\n";
}

请注意,右括号后的分号是多余的。

关于c++ - C++无法弄清楚为什么它会给出误报(newbie),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61818580/

相关文章:

c++ - GLSL:链接后没有事件制服/属性

swift - 在完成 if 语句之前运行以下脚本

javascript - `x < y && y > x` 有任何理由吗?

c++ - istringstream 没有输出正确的数据

python - 将 CMake 用于 Python 中的 C++ 扩展,使用 SWIG 并依赖于预先存在的库

c++ - 将参数传递给函数

c# - 如何在没有多个 if 语句的情况下检查条件?

ios - "If"语句之谜

python - 被简单的代码困住了

c - 具有整数增量的 bool 表达式给出意想不到的结果