Search code examples
cfloating-pointcomparison

C-language floating number brain buster


A friend showed me this c-language code, and I'm very confused with its output. Can any one please explain why is it giving output "It was a piece of black forest cakeThis is weird", instead of "It was a piece of black forest cakeIt was a piece of black forest cake"?

# include <cstdio>

using namespace std;

int main()
{
    float a = 0.5;

    if(a < 0.5) 
        printf("This is Weird");
    else 
        printf("It was a piece of black forest cake");

    float b = 0.7;
    if(b < 0.7)
        printf("This is Weird");
    else 
        printf("It was a piece of black forest cake");

    return 0;
}

Solution

  • This is because 0.5 can be presented as a float exactly, whereas 0.7 cannot. Also both of these are double constants, that is, to store them at their standard precision, they need to be stored in a variable of type double. YOu can get a float constant by suffixing the number with f. Furthermore in if (b < 0.7) comparison the float is converted to double implicitly; 0.7 can be stored as a double more precisely, and thus in this case is a larger number, because the 0.7 was rounded down when stored in a float variable.

    Try also the following code:

    #include <stdio.h>
    
    int main()
    {   
        if (0.7f < 0.7) {
           printf("This is Weird");
        }
        return 0;
    }