用于计算和 IF 语句内部的" | "或" & "之间的差异

Difference between " | " or " & " for calculations and inside IF statement

本文关键字:之间 计算 IF 语句 内部 用于      更新时间:2024-09-27

我正在尝试在 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 不会执行?

this if 语句中的表达式

else if (n3 == n1 | n2) 

相当于

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

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

所以

0 | n2

给出等于n2的非零值。

因此,表达式的结果是布尔true.。

至于这个如果声明

if (n3 == nResult) 

然后nResult计算,nResult = n1 | n2;等于不等于n37

如果你想看看一个数字是否是"一组可能的答案之一",那么有几种方法。

例如,给定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, 5, 9 };
if (std::find(matches.begin(), matches.end(), n) != matches.end()) {
// Matches
}

您可以使用std::set

std::set<int> matches = { 3, 5, 9 };
if (matches.find(n) != matches.end()) {
// Matches
}

您可以使用位图索引:

std::bitset<10> matches = "0001010001";
if (matches[n]) {
// Matches
}

你不能做的是使用|运算符将数字粉碎在一起。