我正在用 C 编写这个大型程序,这是我作业的一部分。我的问题是我的程序正在输出 x = -0.00
而不是 x = 0.00
。我试过像 if(x==-0.00) x=fabs(x)
这样比较,但我读到它不会像 double 那样工作。所以我的问题是还有其他方法可以检查 double 是否等于负零吗?
最佳答案
您可以使用 math.h
中的标准宏 signbit(arg)
。如果 arg
为负,它将返回非零值,否则返回 0 。
来自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.
此外,来自 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.
关于检查 double 是否等于 -0.00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173892/