4
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?

Pascal Cuoq
  • 75,447
  • 6
  • 144
  • 260
  • You might like this blog post: http://blog.frama-c.com/index.php?post/2011/11/08/Floating-point-quiz – Pascal Cuoq Aug 08 '12 at 15:22
  • 1
    exact duplicate of http://stackoverflow.com/questions/1839422/strange-output-in-comparision-of-float-with-float-literal – tinman Aug 08 '12 at 16:55

3 Answers3

8

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.

cnicutar
  • 164,886
  • 23
  • 329
  • 361
1

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

try:

if(lfResult == 19.893196F)
  ...
CapelliC
  • 57,813
  • 4
  • 41
  • 80
0

In if condition, 19.893196 can be taken as double. So the if condition fails.

You should try like following way.

if(lfResult == 19.893196f)

I think it will be helpful to you.

Prasad G
  • 6,474
  • 7
  • 39
  • 65