用于计算和 IF 语句内部的" | "或" & "之间的差异
Difference between " | " or " & " for calculations and inside IF statement
我正在尝试在 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;
等于不等于n3
7
。
如果你想看看一个数字是否是"一组可能的答案之一",那么有几种方法。
例如,给定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
}
你不能做的是使用|
运算符将数字粉碎在一起。
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 计算所有对之间的曼哈顿距离
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 计算车辆之间的距离并设置速度,使距离保持不变,例如 5 米
- 是否有一种标准方法来计算两个 asctime() 值之间的天数
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 对于C++随机访问迭代器(矢量迭代器),迭代器之间的差异是如何计算的?
- 为什么 2 个双精度值之间的差值计算错误?
- C++和Lua之间的简单数学计算不同
- 如何计算大小为 1000 x 1000 的 2D 数组中 2 个元素之间的步幅?C++
- 计算每个维度的两个 3D 矢量之间的角度
- 计算两个uint8_t变量之间差值的最快方法是什么?
- 如何更有效地计算n个字符串之间的不匹配分数?
- 大括号和括号之间的参数计算顺序
- 如何计算两个负整数 c++ 之间的总和
- 为什么CRC计算在C和C 版本之间有所不同
- 如何获得OpenGL在给定高度级别之间计算的值
- C++:对迭代器之间计算距离的类型感到困惑
- c++ |在两个特定点之间计算文件中的行数
- 如何在C++中的正整数和负整数之间计算IF语句中的bool