检查 double 是否等于 -0.00

标签 c double comparison

我正在用 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/

相关文章:

c++ - 如果不使用它,访问数组外的数据是否不正确?

对没有 void 的调用方法感到困惑

C fgets - 捕获溢出的简单方法?

java - JMS/AMQP 代理比较

c - C中奇怪的整数比较

linux - 我需要一个 Win/Linux 的二进制比较工具

C: MD5 给出垃圾作为结果

c - 在 C 中将 double 表示为字符数组

java - 回复 : Convert Double to byte[] array

java - 我的输出只需要两位小数