Click here to Skip to main content
15,888,031 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include<stdio.h>
int main(){
float a=0.7;
if(a<0.7){
printf("true");
}
else{
printf("false");
}
return 0;
}
Posted
Updated 26-Nov-15 18:43pm
v3
Comments
PIEBALDconsult 27-Nov-15 0:44am    
Try printing the value of a and/or use the debugger to see it.

Any thing you write in code must be stored in memory in binary form (0,1 form)
When you write float a=0.7 then a must get the binary value of 0.7.
In binary 0.7 is
C#
b0.1011001100110011001100110011001100110011001100110011001100110...

However, 0.7 is a double-precision literal, whose value is 0.7 rounded to the closest representable double-precision value, which is:
C#
b0.10110011001100110011001100110011001100110011001100110

In decimal, that's exactly:
C#
0.6999999999999999555910790149937383830547332763671875

When you write float a = 0.7, that double value is rounded again to single-precision, and a gets the binary value:
C#
b0.101100110011001100110011

which is exactly
C#
0.699999988079071044921875

in decimal.
When you do the comparison (a < 0.7), you are comparing this single-precision value (converted to double, which does not round, because all single-precision values are representable in double precision) to the original double-precision value.
C#
0.699999988079071044921875 < 0.6999999999999999555910790149937383830547332763671875

the comparison correctly returns true.
Please visit this link for Floating point airthmatic operation
Floating Point Airthmatic[^]
 
Share this answer
 
Comments
Richard MacCutchan 27-Nov-15 3:33am    
Some idiot downvoted you for this excellent explanation. Countered with a 5 (even though you mis-spelled Arithmetic :( )
Hello ,
In C programming language, the floating point constant is double type by default, that's why 0.7 is double type, unless use 'f' or 'F' suffix to indicate float type.Hence the float variable a is less than double constant 0.7.
#include<stdio.h>
int main()
{
    float a=0.7;
    printf("%.10f %.10f\n",0.7, a);
    return 0;
}
</stdio.h>

O/P will be
0.7000000000 0.6999999881

Hence the if condition is satisfied and it prints "true"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900