c puzzle(if statement) [closed]
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..
精彩评论