Here I am getting the output as :d instead of c ......Code:#include<stdio.h> void main(void) { float f=0.7; if(f==.7) printf("c"); else printf("d"); }
If anybody have idea of this , kindly explain me why it becomes like that.??
Here I am getting the output as :d instead of c ......Code:#include<stdio.h> void main(void) { float f=0.7; if(f==.7) printf("c"); else printf("d"); }
If anybody have idea of this , kindly explain me why it becomes like that.??
you are comparing the float f with the double literal .7.Code:if(f==.7)
should give you the result you expect.Code:float f = 0.7f; if(f==.7f)
You should read about floatingpoint numbers and why it is never a good idea to compare them. If you have to you need to prepare for rounding errors.
Kurt
edit: I very much agree with qazah's reply
Last edited by ZuK; 08-19-2006 at 04:18 AM.
I was going to answer, I had it all typed up. Then I decided that it wasn't actually Urgent after all!
Quzah.
Hope is the first step on the road to disappointment.
EDIT: good point quzah...
http://www.catb.org/~esr/faqs/smart-questions.html
As Zuk mentioned, you might want to read up on floating point numbers so you can understand some of the peculiarities of comparing them with each other. Being the nice guy that I am (I am trying to steal the "Mr. Nice" award from Quzah this year.. ^__^) here are some links for you. Lengthy reads to be sure, but the info is by no means useless.
Sun Microsystem's Numerical Computation Guide. (In particular, be sure to read, 'What Every Computer Scientist Should Know About Floating-Point Arithmetic.'
The C-FAQ on floating point numbers.
Steve Hollasch's IEEE Standard 754 Floating Point Numbers
Comparing floating point numbers