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

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

本文介绍了您可以在if语句中使用2个或多个OR条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向论坛提问之前,我曾尝试自己对此进行测试,但是我用于测试此问题的简单代码似乎无法正常工作。

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;
}

它总是返回第一个条件。我的问题是,是否可能有两个以上的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 differenty:

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 ) {

逻辑或运算符( || )定义为如果左侧为true或左侧为false且右侧为true,则为true。由于 2 是真实值( 3 ),因此表达式的计算结果为true,而与<$的值无关c $ c>数字。

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条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:11