while trying the following code

and the output came out as 1.Code:`void main()`

{

float a=0.7;

if(0.7>a)

printf("1");

else

printf("2");

}

can anybody tell why??

is it true that that it is due to double and float comparision.

Printable View

- 07-16-2006sughandhfloat vs Double
while trying the following code

Code:`void main()`

{

float a=0.7;

if(0.7>a)

printf("1");

else

printf("2");

}

can anybody tell why??

is it true that that it is due to double and float comparision. - 07-16-2006Wraithan
Yup, best is to subtact the 2 and compare the absolute value to a range.

EDIT:

Why is due to how floats and doubles are stored... look into how binary decimals are calculated. - 07-16-2006fnoyan
I did not try but, can a computer exactly represent 0.7 in binary? or makes its best approximation? if so, it is expexted to have a wrong result from such a comparison?

You may want to have a look binary representation of data in computers! - 07-16-2006Salem
> void main()

main returns an int - http://faq.cprogramming.com/cgi-bin/...&id=1043284376

> if(0.7>a)

You're comparing a double constant with a float variable.

In the promotion of the float to a double, the value changes, and the expected comparison fails.

Try

if(0.7f>a)

This is sticking plaster, not a solution.

Wraithan's approach is much more sound.

> is it true that that it is due to double and float comparision.

Yes, there are many traps in floating point calculations.