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

新手上路,请多包涵

在论坛上提问之前,我尝试自己对此进行测试,但我用于测试的简单代码似乎不起作用。

 #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 条件?还是我的语法不正确?

原文由 user1116768 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 654
2 个回答

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

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

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

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

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

原文由 Ted Hopp 发布,翻译遵循 CC BY-SA 4.0 许可协议

看起来您想在此链接 or s:

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

上面应该写成

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

或者,通过检查 number 是否在 [1,3] 范围内:

 if (number>=1 && number<=3)

如果您想链接许多 or s( 不是 范围),您可以使用折叠表达式 (C++17) 创建一个辅助模板函数:

例子:

 #include <functional> // std::equal_to
#include <iostream>

// matching exactly two operands
template<class T, class BinaryPredicate>
inline constexpr bool chained_or(const T& v1, BinaryPredicate p, const T& v2)
{
    return p(v1, v2);
}

// matching three or more operands
template<class T, class BinaryPredicate, class... Ts>
inline constexpr bool chained_or(const T& v1, BinaryPredicate p, const T& v2,
                                 const Ts&... vs)
{
    return p(v1, v2) || (chained_or(v1, p, vs) || ...); // fold expression
}

int main() {
    // check if 6  is equal to any of the listed numbers
    if constexpr (chained_or(6, std::equal_to<int>(), 1,3,4,6,9)) {
        std::cout << "6 - true\n";
    }

    // check if 7 is any of the listed numbers
    if constexpr(chained_or(7, std::equal_to<int>(), 1,3,4,6,9)) {
        std::cout << "7 - true\n";
    }
}

chained_or 被实例化时,折叠表达式将展开为:

 (6 == 1 || 6 == 3 || 6 == 4 || 6 == 6 || 6 == 9) // true

(7 == 1 || 7 == 3 || 7 == 4 || 7 == 6 || 7 == 9) // false

原文由 Ted Lyngmo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题