1

Code 1

#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
    printf("IF");
else if (x == 0.1f)
    printf("ELSE IF");
else
    printf("ELSE");
}   

Output: ELSE IF

Code 2

#include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
    printf("IF");
else if (x == 0.5f)
    printf("ELSE IF");
else
    printf("ELSE");
}

Output: IF

Why such a difference in the output? I understand that the variable 'x' will be promoted to 'double' type and '0.1' and '0.5' shall be promoted to 'double' type. However, I am not understanding why output of Code 2 is not outputting ELSE IF. Thanks.

dpaks
  • 375
  • 1
  • 13
  • Read [What every computer scientist should know about floating-point arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). It explains a lot more than what you're asking, but you really should know most of it. – abarnert Aug 27 '14 at 12:21
  • Converting a `double` value to `float` and then that `float` back to `double` is not guaranteed to yield the same `double`. Imagine `double` has 7 digits precision and `float` has 4. Converting `1.234567 (double)` to `1.234 (float)` then back to `1.234000 (double)` – pmg Aug 27 '14 at 12:23
  • I am unable to find the answer from the cited original question. @pmg I understand that but why 0.5 and 0.7 are giving different pattern of output? 0.7 should also be giving ELSE IF right? – dpaks Aug 27 '14 at 12:33
  • My question is specific. I don't think its a duplicate. – dpaks Aug 27 '14 at 12:39
  • While your question is about a specific application, the logic behind it **is** duplicated because you have the same basic problem. Read up on how floats work and the answer will make perfect sense. – Al.Sal Aug 27 '14 at 12:50
  • 2
    Play around with this [floating pointer converter](http://www.h-schmidt.net/FloatConverter/IEEE754.html) if you want to explore the details. _hint: try entering .1 and .5 in the decimal fields and looking at the double precision; also look at the differences in mantissa_ – Al.Sal Aug 27 '14 at 12:51
  • @Al.Sal Clarified! Wish I had the upvote privilege :) – dpaks Aug 27 '14 at 13:00
  • `0.5 (decimal)` is `0.100 (binary float)` and `0.100000 (dinary double)`; `0.1 (decimal)` is `0.001 (binary float)` and `0.001001 (binary double)`. For `0.5` the binary double and the binary float only differ in the number of `0`; for `0.1` the binary representations differ in `1`s too – pmg Aug 27 '14 at 13:10
  • @code_dweller Your answer is specific to the double `0.1`, whereas the duplicate is specific to the double `0.7`. It would be difficult to host a question here for each decimal number that isn't representable exactly in binary floating-point. – Pascal Cuoq Aug 27 '14 at 20:04

0 Answers0