Connecting Tech Pros Worldwide Help | Site Map

What is the reason for this strange floating point result

Newbie
 
Join Date: Oct 2009
Location: chennai
Posts: 4
#1: Oct 6 '09
float a=9.9;
if(a<9.9) printf("true");
else printf("false");
ans:true how is it possible?
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,158
#2: Oct 6 '09

re: What is the reason for this strange floating point result


Easy, floating point numbers are an approximation, approximations can change when operated on.

You have assigned the double constant (9.9)to a float variable so it has converted that double to float.

Then you compare the float variable to a double constant (9.9) so the compiler converts the variable from a float to a double.

So note that in the first 2 lines of your code the constant double 9.9 is implicitly cast down to a float and the implicitly cast back up to a double. With-in those casts it is perfectly with-in the relms of possibility that 9.9 becaomes 9.89999999999999 or less so true gets printed.

To avoid it either define a as a double or use floating point constants 9.9f to avoid implicit casts.

Try reading this too;
Newbie
 
Join Date: Oct 2009
Location: chennai
Posts: 4
#3: Oct 6 '09

re: What is the reason for this strange floating point result


thank u banfa may i know u r name
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,158
#4: Oct 6 '09

re: What is the reason for this strange floating point result


Sorry no; as a matter of personal security policy I don't give out personal information to the general public :-7
Reply