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

Can you use 2 or more OR conditions in an if statement?(您可以在 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;
}

它总是返回第一个条件.我的问题是,是否有可能有超过 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 条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)