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

Recommended Answers

All 3 Replies

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" .

>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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.