Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

Output: does not work

Why does the if condition fail?

like image 914
user1583848 Avatar asked Jan 15 '23 21:01

user1583848


2 Answers

In C floating constants have the type double. Try:

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

Thus the constant 19.893196 has more precision than lfResult.

6.4.4.2 - 4

An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.

like image 106
cnicutar Avatar answered Jan 27 '23 21:01

cnicutar


your literal is a double, casted to float in assignement.

try:

if(lfResult == 19.893196F)
  ...
like image 26
CapelliC Avatar answered Jan 27 '23 21:01

CapelliC