开发者

c puzzle(if statement) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incompl开发者_StackOverflowete, 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.

what is data(number), if the required output from the following statement is is : AMAZING?

main()
{
 int data;
 if(data!=0 && data==-data)
 {
  printf("AMAZING");
 }
}


It'd have to be the minimum value of an integer, i.e. 0x80000000 if it's 32-bits, because that's the only number other than zero that remains the same when negated.

#include <stdio.h>

main()
{
 int data = 0x80000000;
 if(data!=0 && data==-data)
 {
  printf("AMAZING");
 }
}

Result:

AMAZING

As Richard Pennington correctly pointed out, this works because of the two's complement representation of negative numbers. The largest representable positive number is one smaller in absolute value than the largest negative number, so if you try to negate the largest negative number it overflows an int and wraps around, giving back the same number.

For computers that use one's complement, every representable number's negative value can also be represented without overflow so this puzzle doesn't have a solution.


It depends on the size of an integer and how integers are implemented, but on a two's complement machine with 2 byte integers, the answer is -32768.


I don't know what the size of int in my machine. so I used a program to find the max value of int like

void main()
{
   int i;
   do{
       }while(i>i++);
   printf ("data=%d",i);
}

I found the max value of i = -2147483648

assign this to data this will work..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜