请尝试运行以下代码以查看值:
public class Test
{
public static void main(String[] args){
int i = 0, j = 0;
double nan1 = (double)0/0;
double nan2 = (double)0/0;
double nan3 = (double)i/j;
System.out.println(Double.doubleToRawLongBits(nan1) + " == "+ Double.doubleToRawLongBits(nan2) + " is " +
(Double.doubleToRawLongBits(nan1) == Double.doubleToRawLongBits(nan2)));
System.out.println(Double.doubleToRawLongBits(nan1) + " == "+ Double.doubleToRawLongBits((double)0/0) + " is " +
(Double.doubleToRawLongBits(nan1) == Double.doubleToRawLongBits((double)0/0)));
System.out.println(Double.doubleToRawLongBits(nan3) + " == "+ Double.doubleToRawLongBits(nan2) + " is " +
(Double.doubleToRawLongBits(nan3) == Double.doubleToRawLongBits(nan2)));
}
}
在我的 Mac 上,它产生以下输出:
9221120237041090560 == 9221120237041090560 is true
9221120237041090560 == 9221120237041090560 is true
-2251799813685248 == 9221120237041090560 is false
这个陷阱在doubleToRawLongBits 方法的 Javadoc 中有记录:
如果参数是 NaN,则结果是表示实际 NaN 值的长整数。与 doubleToLongBits 方法不同,doubleToRawLongBits 不会将所有编码 NaN 的位模式折叠为单个“规范”NaN 值。