NOT(〜)vs否定(!) [英] NOT(~) vs NEGATION(!)

查看:54
本文介绍了NOT(〜)vs否定(!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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的值是~-10,因此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…111111110.
  • ~ 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 is 0.

但是:

  • !01!anythingElse0
  • -1不是0
  • !-1仍然是0
  • !0 is 1, !anythingElse is 0
  • -1 is not 0
  • !-1 is still 0

如果您实际上想循环包含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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆