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));
System.out.println(Double.doubleToRawLongBits(nan1) == Double.doubleToRawLongBits((double)0/0));
System.out.println(Double.doubleToRawLongBits(nan3) == Double.doubleToRawLongBits(nan2));
输出:
true
true
false
请帮助我,输出的前两个是
true
,最后一个是false
。请告诉我 Double.doubleToRawLongBits()方法的实际工作是什么。 最佳答案
请尝试运行以下代码以查看值:
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
Java文档中针对doubleToRawLongBits method记录了这个陷阱: