Can you use 2 or more OR conditions in an if statement?(您可以在 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 条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您可以在 if 语句中使用 2 个或更多 OR 条件吗?
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01