且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您可以在 if 语句中使用 2 个或更多 OR 条件吗?

更新时间:2023-11-14 20:22:58

您需要以不同的方式编写测试代码:

You need to code your tests differently:

if (number==1 || number==2 || number==3) {
    cout << "Your number was 1, 2, or 3." << endl;
}
else if (number==4 || number==5 || number==6) {
    cout << "Your number was 4, 5, or 6." << endl;
}
else {
    cout << "Your number was above 6." << endl;
}

你这样做的方式,第一个条件被解释为好像是这样写的

The way you were doing it, the first condition was being interpreted as if it were written like this

if ( (number == 1) || 2 || 3 ) {

逻辑或运算符 (||) 被定义为在左侧为真或左侧为假而右侧为真时评估为真值.由于 2 是真值(3 也是如此),因此无论 number 的值如何,表达式都会计算为真.

The logical or operator (||) is defined to evaluate to a true value if the left side is true or if the left side is false and the right side is true. Since 2 is a true value (as is 3), the expression evaluates to true regardless of the value of number.