我有一个程序示例:
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.
因此,如果分数为 0,符号为 0,则为 +0.0。
如果分数为 0,符号为 1,则为 -0.0。
这些数字具有相同的值,但它们在正/负检查方面有所不同。这意味着,例如,如果:
x = +0.0;
y = -0.0;
然后你应该看到:
(x -y) == 0
但是,对于 x,OP 的代码将使用“x 更大”,而对于 y,它将使用“x 更小”。
编辑: Artur的 answer和 Jeffrey Sax对此答案的评论澄清了 x < 0
测试的差异在 OP 的问题中实际上是一个编译器优化,实际上是对 x < 0
的测试对于正面和负面0
应始终为 false
.
关于c - 双值作为负零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19922379/