c - 双值作为负零

标签 c

我有一个程序示例:

int main()
{
    double x;
    x=-0.000000;
    if(x<0)
    {
        printf("x is less");
    }
    else 
    {
        printf("x is greater");
    }
}

为什么控制进入第一个语句 - x 较少。什么是 -0.000000?

最佳答案

IEEE 754 定义了一个非常常用的标准 float 。可以看到它的结构here :

Finite numbers, which may be either base 2 (binary) or base 10 (decimal). Each finite number is described by three integers: s = a sign (zero or one), c = a significand (or 'coefficient'), q = an exponent. The numerical value of a finite number is

  (−1)^s × c × bq

where b is the base (2 or 10). For example, if the sign is 1 (indicating negative), the significand is 12345, the exponent is −3, and the base is 10, then the value of the number is −12.345.

Double FP number

因此,如果分数为 0,符号为 0,则为 +0.0。
如果分数为 0,符号为 1,则为 -0.0。

这些数字具有相同的值,但它们在正/负检查方面有所不同。这意味着,例如,如果:

x = +0.0;
y = -0.0;

然后你应该看到:

(x -y) == 0

但是,对于 x,OP 的代码将使用“x 更大”,而对于 y,它将使用“x 更小”。

编辑: ArturanswerJeffrey Sax对此答案的评论澄清了 x < 0 测试的差异在 OP 的问题中实际上是一个编译器优化,实际上是对 x < 0 的测试对于正面和负面0应始终为 false .

关于c - 双值作为负零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19922379/

相关文章:

C 代码永远运行*

c - 为什么 FILE 结构实例的大小在 64 位操作系统中为 216 字节,在 32 位操作系统中为 148 字节?

c - 如何向 Bit Torrent Tracker 发送获取请求

检查变量是否存在

c++ - OpenMP 库规范

c - 在linux中如何知道从C中设置IP地址是成功还是失败

c++ - 在分配给指向固定数组的指针期间没有指针衰减

c - Valgrind-snprintf : Conditional jump or move depends on uninitialised value(s)

c - 柏林噪声方 block 不匹配

c - 您如何构建Pion mediadevices webrtc示例?