Question

My code is

void main()
{
    float a = 0.7;
    if (a < 0.7)
        printf("c");
    else
        printf("c++");
} 

It prints C and this is fine as a treated as double constant value and its value will be 0.699999 which is less than 0.7.

Now if I change the value to 0.1,0.2,0.3 till 0.9 in a and also at if condition then it prints C++, apart from 0.7 and 0.9 that mean both are equal or a is greater.

Why this concept not consider for all value?

Was it helpful?

Solution

What "concept" are you talking about?

None of the numbers you mentioned are representable precisely in binary floating-point format (regardless of precision). All of the numbers you mentioned end up having infinite number of binary digits after the dot.

Since neither float nor double have infinite precision, in float and double formats the implementation will represent these values approximately, most likely by a nearest representable binary floating-point value. These approximate values will be different for float and double. And the approximate float value might end up being greater or smaller than the approximate double value. Hence the result you observe.

For example in my implementation, the value of 0.7 is represented as

+6.9999998807907104e-0001 - float
+6.9999999999999995e-0001 - double

Meanwhile the value of 0.1 is represented as

+1.0000000149011611e-0001 - float
+1.0000000000000000e-0001 - double

As you can see, double representation is greater than float representation in the first example, while in the second example it is the other way around. (The above are decimal notations, which are rounded by themselves, but they do have enough precision to illustrate the effect well enough.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top