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.
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.
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.
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!
> 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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.