Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why if(a==2.3) evaluates false when float a=2.3 [duplicate]

Tags:

c

#include<stdio.h>

void main()
{
    float a = 2.3;
    if(a == 2.3) {
        pritnf("hello");
    }
    else {
        printf("hi");
    }
}

It prints "hi" in output, or we can say that if condition is getting false value.

#include<stdio.h>

void main()
{
    float a = 2.5;
    if(a == 2.5)
        printf("Hello");
    else
        printf("Hi");
}

It prints hello.

like image 695
Hariom Avatar asked Dec 06 '22 16:12

Hariom


1 Answers

The variable a is a float that holds some value close to the mathematical value 2.3.

The literal 2.3 is a double that also holds some value close to the mathematical value 2.3, but because double has greater precision than float, this may be a different value from the value of a. Both float and double can only represent a finite number of values, so there are necessarily mathematical real numbers that cannot be represented exactly by either of those two types.

In the comparison a == 2.3, the left operand is promoted from float to double. This promotion is exact and preserves the value (as all promotions do), but as discussed above, that value may be a different one from that of the 2.3 literal.

To make a comparison between floats, you can use an appropriate float literal:

assert(a == 2.3f);
//             ^
like image 60
Kerrek SB Avatar answered Dec 08 '22 05:12

Kerrek SB