逻辑运算符 & 和 | 的区别
difference between logical operators & and |
|是 OR 而 & 是 AND。
我有以下代码,它们工作相反。
int a = 0;
int b = 0;
int c = -1;
if ((a | b | c) == 0)
{
textBox8.Text = "everything 0";
}
else
{
textBox8.Text = "something is not a 0"; // <- code goes here
}
if ((a & b & c) == 0)
{
textBox9.Text = "everything 0"; // <- code goes here
}
else
{
textBox9.Text = "something is not a 0";
}
为什么我有这个结果?
https://i.stack.imgur.com/0Afv6.jpg
(a | b | c) == 0
并不意味着“a 为零或 b 为零或 c 为零”。为此,您需要 (a==0 | b==0 | c==0)
(您也可以使用 ||
,它会在一个操作数为真后停止求值)。
对于数字操作数,|
是一个 bitwise "OR" operator,您可以单独阅读。 ||
对布尔操作数以外的任何东西都无效,所以养成使用 ||
的习惯会很有用,除非你 明确地 不想要短的-电路。这样,当您 缩进 将其用作逻辑运算符时,您就不会不小心将其用作按位运算符。 (例如,在这种情况下可能是编译器错误)。
|是 OR 而 & 是 AND。
我有以下代码,它们工作相反。
int a = 0;
int b = 0;
int c = -1;
if ((a | b | c) == 0)
{
textBox8.Text = "everything 0";
}
else
{
textBox8.Text = "something is not a 0"; // <- code goes here
}
if ((a & b & c) == 0)
{
textBox9.Text = "everything 0"; // <- code goes here
}
else
{
textBox9.Text = "something is not a 0";
}
为什么我有这个结果?
https://i.stack.imgur.com/0Afv6.jpg
(a | b | c) == 0
并不意味着“a 为零或 b 为零或 c 为零”。为此,您需要 (a==0 | b==0 | c==0)
(您也可以使用 ||
,它会在一个操作数为真后停止求值)。
对于数字操作数,|
是一个 bitwise "OR" operator,您可以单独阅读。 ||
对布尔操作数以外的任何东西都无效,所以养成使用 ||
的习惯会很有用,除非你 明确地 不想要短的-电路。这样,当您 缩进 将其用作逻辑运算符时,您就不会不小心将其用作按位运算符。 (例如,在这种情况下可能是编译器错误)。