开发者

c question for beginners [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. 开发者_如何学JAVA
main()
{
  int x=5,y=3;
  x=x+~y+1;
  printf("%d",x);
}

What would the output be?


If your question was "What does this output?", why didn't you just type it in and test it?

#include <stdio.h>

int main (void) {
    int x=5,y=3;
    x = x + ~y + 1;
    printf ("%d\n", x);
    return 0;
}

This outputs 2 on my system. How about yours?


If you print out y and ~y, you'll get 3 and -4 respectively (on a two's complement architecture).

That's because, with two's complement, you can get the negative of a number by inverting all the bits then adding 1. So ~y + 1 (the tilde means "invert all bits") is effectively -y.

   x + ~y + 1
=  x + (~y + 1)
=  x + (-y)
=  x - y
=  5 - 3
=  2

Aside: I don't think that ISO actually mandates an underlying two's complement architecture for storing numbers so that may not work on all implementations. However, it's been a long time since I saw such a beast. And, to be honest, if you want to get the negative of a number, why wouldn't you just use -y?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜