Regarding floats and comparison operator in C

int main() { float lfResult = 19.893196; if(lfResult == 19.893196) printf("Works"); else printf("does not work"); getch(); return 0; } 

Exit: not working

Why is the if condition satisfied?

+4
source share
3 answers

In C, floating constants are of type double . Try:

 float lfResult = 19.893196f; if(lfResult == 19.893196f) ^ 

Thus, the constant 19.893196 has a higher accuracy than lfResult .

6.4.4.2 - 4

Unsuf fixed fl oating constant has type double . If it satisfies the letter f or F, it is of type float. If it is satisfied with the letter l or L, it is of type long double.

+8
source

your literal is double cast for assignment swimming.

to try:

 if(lfResult == 19.893196F) ... 
+1
source

In case the condition, 19.893196 can be considered double. Thus, the if condition does not work.

You should try as follows.

 if(lfResult == 19.893196f) 

I think it will be useful for you.

0
source

All Articles