File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes C / C++ and the fly likes float and double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "float and double" Watch "float and double" New topic

float and double

aaka jain

Joined: May 16, 2013
Posts: 12
float fl = 10.5;
double dbl = 10.5
if(fl ==dbl)
printf("UNITED WE STAND");

it is a c program
I am getting answer UNITED WE STAND in the above program and if I change the values like fl=10.7 and dbl=10.7 I am getting answer DIVIDE AND RULE ,can anyone please explain me why are we getting different outputs
Maxim Karvonen
Ranch Hand

Joined: Jun 14, 2013
Posts: 117
Not all floating-point numbers can be represented precisely by a computer. 10.7 is not a valid "exact" value for both float and double. It is represented by values very close to original but these values are not equal to 10.7. These representations differs slightly between float and double (float has less precision). So when you convert floating 10.7 value to double you get not a 10.7 double but something very close to it. However 10.5 can be represented precisely in floating-point type so values are equal even after float->double conversion.

You may read more about floating point numbers here.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

and note - this is not unique to C/C++. It happens in many languages that use the IEEE spec on floating point numbers.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: float and double
jQuery in Action, 3rd edition