NOT(〜)vs否定(!) [英] NOT(~) vs NEGATION(!)
问题描述
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int i=-5;
while(~(i))
{
cout<<i;
++i;
}
}
输出为-5,-4,-3,-2. 它不应该打印直到-1的值吗?为什么只显示-2? 并且请向我解释非"运算符和否定"运算符之间的区别.每当我编写程序时,它们都是错误的来源.
The output is -5,-4,-3,-2. Shouldn't it print values till -1?Why is it only till -2. And please explain me the difference between 'not' and 'negation' operators.When ever I write a program they were the source for bugs.
while(i)
我知道循环条件对于正数和负数(除0外)都是正确的.
I know that the loop condition will be true for positive and negative i's except 0.
while(!i) vs while(~i)
对于上面两个循环执行的'i'值是什么?
For what values of 'i' the above two loops get executed?
推荐答案
当i
到达-1
时,~i
的值是~-1
或0
,因此while
循环停止执行. !
运算符之所以起作用,是因为它做了完全不同的事情.对于0
值,其结果为1
,对于所有其他值,其结果为0
. ~
是按位取反.
When i
gets to -1
, the value of ~i
is ~-1
, or 0
, so the while
loop stops executing. The !
operator works because it does something completely different; it results in 1
for 0
values and 0
for all other values. ~
is a bitwise negation.
更多细节:
-
~
接受数字中的每个位并进行切换.因此,例如10010 2 将变为01101 2 -
-1
当二进制补码有符号整数时都是二进制的. -
~0b…11111111
是0
.
~
takes each bit in a number and toggles it. So, for example, 100102 would become 011012-1
is all ones in binary when a two's complement signed integer.~0b…11111111
is0
.
但是:
-
!0
是1
,!anythingElse
是0
-
-1
不是0
-
!-1
仍然是0
!0
is1
,!anythingElse
is0
-1
is not0
!-1
is still0
如果您实际上想循环包含i == -1
,只需使用while (i)
而不是while (~i)
.
And if you actually want to loop including i == -1
, just use while (i)
instead of while (~i)
.
这篇关于NOT(〜)vs否定(!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!