B
bhawna great
float a=0.7;
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
This program:float a=0.7;
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
You've mixed float and double. Did you forget to write 0.7f ?bhawna said:float a=0.7;
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
bhawna great said:float a=0.7;
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
Chip Coldwell said:Actually, the answer is deep. Mostly the problem is that not all
decimal fractions have exact binary representations. For numbers that
do, you will get the expected results. Try again, setting "a" equal
to
0.5 = 1/2
0.25 = 1/4
0.125 = 1/8
0.75 = 3/4
0.625 = 5/8
0.0625 = 1/16
0.6875 = 22/32
and you'll see that it works as expected. All of these numbers have
exact representations as binary fractions (denominator a power of
two), whereas 0.7 doesn't. The closest floating point number to 0.7
is represented as 0x3F333333 in IEEE 754 single precision,
3f333333 is 0011 1111 0011 0011 0011 0011 0011 0011 in binary
seee eeee emmm mmmm mmmm mmmm mmmm mmmm
s = 0 (sign is positive)
e = 01111110 = 0x7e (exponent is -1 -- the exponent bias is 127)
m = (1)011 0011 0011 0011 0011 0011 = 0x00b33333
(mantissa is 11744051 * 2**(-23))
So the exact value is 11744051/16777216 = 0.699999988079071044921875
Now, on an architecture such as the POWER6 CPU from IBM that supports
decimal floating point (as opposed to binary), you could in principle
represent decimal literals exactly.
Chip
float a=0.7;
if(0.7>a)
printf("Hi");
else
printf("Hello");
output is Hi
Why?
Barry said:If not in binary, how does the power6 store information?
[...]Chip Coldwell said:The POWER6 CPU does store information in binary; however, it has a
floating-point unit that is capable of doing computations in decimal
arithmetic. This is nothing new; IBM mainframes and everyday pocket
calculators have done floating point in decimal for a very long time.
float a = 0.7f ;
...
if ( 0.7f > a )
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.