Hi, everyone! The following code would produce -0.00000. But I want it be 0.00000. How can I do that?
Thank you in advance!Code:int main (void) { double a=0.0, b=-1.0; printf("%10.5f\n", a/b); return 0; }
Hi, everyone! The following code would produce -0.00000. But I want it be 0.00000. How can I do that?
Thank you in advance!Code:int main (void) { double a=0.0, b=-1.0; printf("%10.5f\n", a/b); return 0; }
Use fabs() ?
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.
put -(a/b) instead of a/b..
0 is neither positive nor negative..so dont take it serious buddy
0 compares equal to -0 so it doesn't matter, well until you go and print it that is, in which case -> fabs.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Annex F of the C standard says the floating point support for IEC 60559 encompasses the IEEE 754 standard. My IEEE membership doesn't give me access to the standard and I'm too cheap to pay for it, but according to Wikipedia, IEEE 754 guarantees that 0 and -0 compare equal. So unless you have a non-conforming compiler in this regard (which you should probably toss), you should be fine with that comparison.
It doesn't bother anybody that there's such thing as a negative zero?
I can possibly see where an "almost zero" could be rounded up to zero but a sloppy binary-to-decimal converter could keep the negative sign.
I can also be possibly persuaded thatcan get an obscure number on the stack, when it's exported from the floating point registers... but I'm certain that if the result were saved to a variable, that its negative sign would not be retained.Code:printf("%10.5f\n", a/b);
I highly doubt one could force a variable test = -0 no matter how hard one tried.
Overall it sounds like a compiler bug.
A compiler need not support IEC 60559, though. From Annex F: "An implementation that defines __STDC_IEC_559__ shall conform to the specifications in this annex."
Even stickier is the fact that the whole IEEE floating point thing is C99 only. Not that C89 can't support IEEE floats (most implementations do, I suspect), but you can't check a macro for conformance like you can in C99.
Technically C does not required floats to distinguish -0 from +0, but it's pretty universal for floats to be stored in IEEE form, which has an explicit sign bit, along with mantissa and exponent. IEEE also requires zero/negative to be stored as -0, and zero/positive to be stored as +0. The difference also comes into play with discontinuous functions with branch cut.