'How does "0.7 > a" return true where "float a = 0.7"? [duplicate]

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?



Solution 1:[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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Felipe Marques