File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

float and double

aaka jain
Greenhorn

Joined: May 16, 2013
Posts: 12
main(){
float fl = 10.5;
double dbl = 10.5
if(fl ==dbl)
printf("UNITED WE STAND");
else
printf("DIVIDE AND RULE")
}

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: 102
    
  10
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
Bartender

Joined: Oct 02, 2003
Posts: 11256
    
  16

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: http://aspose.com/file-tools
 
subject: float and double