How does "0.7 > a" return true where "float a = 0.7"?

369 Views Asked by At

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?

1

There are 1 best solutions below

5
Felipe Marques On

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;