0

I am trying a simple program in which I have taken a float number and comparing it with fixed numbers 0.5,0.7, 0.8 each time the output is different than expected. My code is

#include<stdio.h>
int main*()
{
    float a = 0.5;
    if (a > 0.5)
        printf("greater");
    else if (a < 0.5)
        printf("less");
    else if (a == 0.5)
        printf("equal");

}

Now the crazy part is when I execute it with 0.5 value of a and replacing 0.5 with 0.7 as in code it prints equal, if with 0.7 then less and if with 0.8 then it prints greater. I can't figure it out. Can anybody explain this Please? I'm using codeblocks 16.01 for this and tried in Turbo C++ as well.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Rohit
  • 552
  • 3
  • 15
  • 1
    It's not *only* because `0.7` cannot be exactly encoded - that inexactness would be *repeatable*. It is because `0.7` is type `double`. It is then converted to `float`, which is compared with `double`. That value `0.7` cannot be encoded exactly in either `float` or `double`, but because they are different types, their inexact values are *different* inexact values. – Weather Vane Mar 03 '17 at 11:07
  • just tested your code on https://www.tutorialspoint.com/compile_c_online.php and it always works fine. – SHAHS Mar 03 '17 at 13:37

0 Answers0