问题描述
在论坛上提问之前,我尝试过自己测试,但我测试它的简单代码似乎不起作用.
I tried to test this myself before asking on the forum but my simple code to test this didn't seem to work.
#include <iostream>
using namespace std;
int main() {
cout << "Enter int: ";
int number;
cin >> number;
if (number==1||2||3) {
cout << "Your number was 1, 2, or 3." << endl;
}
else if (number==4||5||6) {
cout << "Your number was 4, 5, or 6." << endl;
}
else {
cout << "Your number was above 6." << endl;
}
return 0;
}
它总是返回第一个条件.我的问题是,是否有可能有超过 2 个 OR 条件?还是我的语法不正确?
It always returns the first condition. My question is, is it even possible to have more than 2 OR conditions? Or is my syntax incorrect?
推荐答案
您需要以不同的方式编写测试代码:
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
.
这篇关于您可以在 if 语句中使用 2 个或更多 OR 条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!