gpt4 book ai didi

java - 当没有符号的 0 等于并且更普遍被认为是正确的时候,为什么 Java 在 0 前面打印一个负号?

转载 作者:搜寻专家 更新时间:2023-11-01 01:52:44 26 4
gpt4 key购买 nike

在 java 中,以下代码的输出是 0.0,-0.0,-0.0。这些不同答案的原因是什么?

System.out.print((0.0 % -1)+","+(-0.0 % 1)+","+ (-0.0 % -1));

最佳答案

模运算符只会取一个数除以它的余数。

0 除以 -1 得到 0,所以结果为 0。

float 和 double 确实知道 -0 和 +0 之间的区别,所以当你取 -0 的余数时,你会得到 -0,因为它仍然是 0 和 1(或 -1)之间的有效数字.

这是 float 工作方式的一个怪癖,也是 0 的特殊属性,因为其他数字并不适用:

System.out.println((0.0 % -1)+","+(-0.0 % 1)+","+ (-0.0 % -1));

System.out.println((0 % -1)+","+(-0 % 1)+","+ (-0 % -1));

System.out.println((3 % -1)+","+(-3 % 1)+","+ (-3 % -1));

显示:

0.0,-0.0,-0.0 
0,0,0
0,0,0

由于需要引用:

float 在 IEEE_754-1985 中定义:

http://en.wikipedia.org/wiki/IEEE_754-1985

有整个维基百科页面讨论负零:

http://en.wikipedia.org/wiki/Negative_zero

这也至少部分地解释了为什么模的工作原理是:

According to the IEEE 754 standard, negative zero and positive zero should compare as equal with the usual (numerical) comparison operators, like the == operators of C and Java.

由于模运算产生一个 >= 到 0 且小于给定值的数字,那么 -0 已经满足 >= 要求(因为 -0 == 0)并且操作可以立即结束。

关于java - 当没有符号的 0 等于并且更普遍被认为是正确的时候,为什么 Java 在 0 前面打印一个负号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com