Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

float and double

 
aaka jain
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 121
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12097
30
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and note - this is not unique to C/C++. It happens in many languages that use the IEEE spec on floating point numbers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic