0

void main()
{
float a = 0.7;
if(a < 0.7)
printf("YES");
else
printf("NO);

}

But this function always prints NO.

And when it is made Greater than 0.7

It shows YES

Why is it so with float variable


Ashwin Perti

4
Contributors
3
Replies
4
Views
12 Years
Discussion Span
Last Post by Balachandran
0

It prints "NO" because the condition you have given is a<0.7 not a<=0.7. Since a=0.7 it gives output as "NO" .

0

>But this function always prints NO.
The only thing that function should print is a compiler error and at least one warning if your compiler is half decent.

>Why is it so with float variable
It has nothing (or rather, little) to do with your choice of types. 0.7 is not less than 0.7. But since this answer will lead you to a pitfall, be careful comparing floating-point types for equality. Seemingly equal values can, and often will, not compare as equal due to the imprecision inherent in floating-point types.

0

hi,
i have tried ur program already and i got the output as YES only.i suppose that you got this question from EXPLORING C by Yashavant Kanetkar.You get the answer as yes due to precision considerations.C always stores a variable in the highest possible precision.To get the (mathematically) correct answer declare variable 'a' as long double.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.