I am making this big program in C, which is a part of my homework. My problem is that my program is outputing x = -0.00
instead of x = 0.00
. I have tried comparing like if(x==-0.00) x=fabs(x)
but I've read that it won't work like that with doubles. So my question is are there any other ways to check if double is equal to negative zero?
You can use the standard macro signbit(arg)
from math.h
. It will return nonzero value if arg
is negative and 0 otherwise.
From the man page:
signbit()
is a generic macro which can work on all real floating- point types. It returns a nonzero value if the value of x has its sign bit set.This is not the same as x < 0.0, because IEEE 754 floating point allows zero to be signed. The comparison -0.0 < 0.0 is false, but signbit(-0.0) will return a nonzero value.
NaNs and infinities have a sign bit.
Also, from cppreference.com:
This macro detects the sign bit of zeroes, infinities, and NaNs. Along with
copysign
, this macro is one of the only two portable ways to examine the sign of a NaN.
Very few calculations actually give you a signed negative zero. What you're probably observing is a negative value close to zero that has been truncated by your formatting choice when outputting the value.
Note that -0.0
is defined to be equal to 0.0
, so a simple comparison to 0.0
is enough to verify a signed zero.
If you want to convert an exact signed zero -0.0
to 0.0
then add 0.0
to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With