用于计算的“ |”或“&”与内部IF语句之间的差异

问题描述

我正在尝试在IF(或SWITCH)语句中使用|来比较变量是否等于数字或另一个 但是我发现(以下代码中的示例为例),对我想要比较的两个数字使用|运算符与将||进行两次比较的结果相同。但是,如果我声明另一个使用|对这两个数字进行或运算的变量,则if语句将不会执行:

(这是“几乎”完整的代码

using namespace std;
short n1 = 5,n2 = 3,n3,nResult;
n3 = 3; // used for two comparisons
nResult = n1 | n2; // used for the second comparison (IF statement)
    
bitset<16> n1_b(n1),n2_b(n2),n3_b(n3),nr_b(nResult); // I used bitset to check their binary value
    
if (n3 == nResult) 
    cout << "nResult YES";
else if (n3 == n1 | n2) 
    cout << "n1 | n2 YES";
    
/* cout << endl << n1_b << endl << n2_b << endl << n3_b << endl << endl << nr_b; */

输出始终为n1 | n2 YES。 为什么在IF语句中使用m3 == n1 | n2会得到与使用n3 == n1 || n3 == n2相同的结果,为什么我之前执行ORed不会执行?

解决方法

此if语句中的表达式

else if (n3 == n1 | n2) 

等同于

else if ( ( n3 == n1 ) | n2) 

子表达式n3 == n13 == 5)产生在表达式中使用的布尔值false,该布尔值被隐式转换为0

所以

0 | n2

给出的非零值等于n2

因此,表达式的结果为布尔值true

关于此if语句

if (n3 == nResult) 

然后像nResult计算的nResult = n1 | n2;等于7,不等于n3

,

如果您想查看数字是否为“一组可能的答案之一”,那么有几种方法。

例如,给定n和类似3,5,9的集合,您可以使用if

if (n == 3 || n == 5 || n == 9) {
  // Matches
}

您可以使用switch

switch (n) {
  case 3:
  case 5:
  case 9:
    // Matches
    break;
}

您可以使用std::vector

std::vector<int> matches = { 3,9 };

if (std::find(matches.begin(),matches.end(),n) != matches.end()) {
  // Matches
}

您可以使用std::set

std::set<int> matches = { 3,9 };

if (matches.find(n) != matches.end()) {
  // Matches
}

您可以使用位图索引:

std::bitset<10> matches = "0001010001";

if (matches[n]) {
  // Matches
}

您不能使用|运算符将数字粉碎在一起。