Home > Enterprise >  Comparing float values in if condition is not working in C [duplicate]
Comparing float values in if condition is not working in C [duplicate]

Time:09-21

int main() {
// Write C code here
float x = 3.14;
if(x==3.14){
    printf("true");
}

return 0;

}

I am unable to execute this part of the if conditon.

CodePudding user response:

Instead of writing x = 3.14; write x = 3.14f and instead of if(x == 3.14) write if(x == 3.14f) because 3.14 is a double and 3.14f is a float.

CodePudding user response:

3.14 is a double constant.

float x = 3.14; converts 3.14 to a float.

x==3.14 compares the float in x to the double 3.14. They are not equal.

The double and float formats use different representations of numbers and cannot represent all of the same values. (The float numbers are a subset of the double numbers.)

x == 3.14f will compare the float in x to the float constant 3.14f.

Preferably, use float constants with float types, so initialize x with float x = 3.14f; rather than float x = 3.14;.

CodePudding user response:

Wrap it inside float: if(x==float(3.14))

Edit: realised it's in c. Why not cast (float) 3.14?

  • Related