为什么if语句无效

Why is if statement not working

本文关键字:无效 语句 if 为什么      更新时间:2023-10-16

我是编程新手,无法解决这个问题,我已经到处寻找答案。当从function2传递cin >> 1时,似乎不会读取function1 if (m != 0 || 1)中的if语句。这是我的代码,任何帮助都将不胜感激。

#include <iostream>
void function1(int i);
int main() {
    using namespace std;
    int i;
    function1(i);
return 0;
}
----------------------------------------------------------------------------
#include <iostream>
void function2();
void function1(int i) {
    using namespace std;
    if (i != 0 || 1 ) /* not working when the variable 'i' is passed from function2 */ {     
    cout << endl << "i != 0 || 1" << endl;
    function2();
    }
    else if (i == 0 || 1) {
        if (i == 0) {
            cout << endl << "m == 0" << endl;
        }
        else if (i == 1) {
            cout << endl << "m == 1" << endl;
        }
    }
}
----------------------------------------------------------------------------
#include <iostream>
void function1(int i);
void function2() {
    using namespace std;
    int i;
    cout << endl << "type 0 or 1" << endl;
    cin >> i;    /* type 1 or 0 in here */
    function1(i);
}

尽管user154248的答案(至少部分)是正确的,但您可能会感兴趣的是为什么。。。

原因是operator!=具有较高的优先级(即在operator||之前进行评估)。所以你的if子句等价于if((i != 0) || 1)

此外,如果在期望布尔参数的表达式中使用任何不等于0(null/zero)的值,则会将其计算为true,因此可以得到if((i != 0) || true)。现在,无论i != 0的求值结果是什么,总表达式x || true都将产生true

最后–我们回到了用户154248的答案。。。

然而,还有一个问题:i != 0 || i != 1也总是求值为true:如果i等于0,i != 1求值为true,如果i等于1,i != 0求值为true…

您实际需要的是i != 0 && i != 1

尝试更改此项:

if (i != 0 || 1 )

对此:

if (i != 0 || i != 1 )