-1
#include <stdio.h>

int main(void)

{
    float c;

    c = 4.7;

    if(c == 4.7)

    {
        printf("Hello World");
    }
    return 0;
}

The problem here is with the float data type... To print Hello world we need to write (float)4.7 why??

ani627
  • 5,578
  • 8
  • 39
  • 45
  • 4
    because floating point representation of a number is imprecise. Read this http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – suspectus Sep 27 '14 at 07:58
  • 4
    [How dangerous is it to compare floating point values?](http://stackoverflow.com/questions/10334688/how-dangerous-is-it-to-compare-floating-point-values) – ani627 Sep 27 '14 at 08:00
  • 1
    You will want to read [**The Floating-Point Guide - What Every Programmer Should Know ...**](http://floating-point-gui.de/). The problem is you are not comparing what you think you are. – David C. Rankin Sep 27 '14 at 08:10
  • Only those float values which have an exact binary representation can be compared, for eg : if you do 2.5 == 2.5. – Abhishek Choubey Sep 27 '14 at 08:24

1 Answers1

4

4.7 has the type double, and c has the type float. If you compare a float and a double, the float first gets converted to a double. So your if is doing: (double)(float)4.7 == 4.7, which is false, because when converting 4.7 to float there was a loss of precision, and the number changed a tiny bit.

You can do an approximate comparison like this if (fabs(f - 4.7) < 1e-10).

pts
  • 80,836
  • 20
  • 110
  • 183
  • 1
    Also, OP should know: compiler probably represents `4.7` as `4.699999...`. That's why `(float)4.7 != (double)4.7`. But compiler can precisely represent some other numbers, like `1`. And OP's program can work without typecasting with these numbers. – HolyBlackCat Sep 27 '14 at 08:28
  • 1
    `if (f == 4.7f)` works correctly. – Paul Hankin Sep 27 '14 at 08:47
  • Yes. Of course `4.7f == 4.7f`, because they have the same precision. – HolyBlackCat Sep 27 '14 at 08:50
  • 2
    "4.7 as 4.699999..." -- those have exactly the same value (see https://www.youtube.com/watch?v=TINfzxSnnIE). What you really mean to say is that the the binary representation of 4.7 is actually slightly smaller than 4.7 . – Jim Balter Sep 27 '14 at 09:42