-2

Consider the code below:

float a = 0.7;
if(0.7 > a)
    printf("Hi");
else
    printf("Hello");

// The output will be: Hi

Why does the if statement in here return true? But if I replace a with 0.7 then it returns false? How is 0.7 greater than a? and this doesn't happen with 0.5 or something else. Why does this happen?

Ashkan Kahbasi
  • 69
  • 1
  • 1
  • 7

1 Answers1

1

0.7 alone is not a float but a double and since they are different data types with different precisions the values are not the same. In this case you have to explicitly tell 0.7 is float by adding "f" at the end:

    float a = 0.7;
    if(0.7f > a)
        printf("Hi");
    else
        printf("Hello");

    return 0;

Or just change the data type of "a" variable to double:

    double a = 0.7;
    if(0.7 > a)
        printf("Hi");
    else
        printf("Hello");

    return 0;
  • that has been explained in the duplicates. Don't post answers to this – phuclv Feb 24 '22 at 09:21
  • If that's true as a general rule then why does this only happen with 0.7 and not other floating-point numbers? – Ashkan Kahbasi Feb 24 '22 at 09:23
  • 1
    The `0.5` in the question can be exactly represented, in binary `float` and `double`. And whole numbers can be exactly represented up to the limit of precision. – Weather Vane Feb 24 '22 at 09:24
  • 2
    @Ashkan It does happen with other floating point numbers, for example 0.9. – Ian Abbott Feb 24 '22 at 10:31
  • If the fractional part can be expressed exactly by 2^-1 + ... + 2^-n with n <= N (N being the number of bits provided for the fractional part, this depends on the number of bits necessary for the integer part), then a floating point number is exactly represented. Else not. It's that simple. – the busybee Feb 24 '22 at 13:40