public class Test {
  public static void main(String args[])
{
double i = 0.0/0.0;
if(i!=i)
{
System.out.print("123");
}
else
{
System.out.print("456");
} }}代码如上,int型0/0会抛出除0的异常,但是double却不会。这个i的定义方法其实就是java.lang.Double类里的Nan常量的定义方法,很想知道为什么运行不会出错。同时这段程序的运行结果是
123。很另人迷惑,希望高手指点。

解决方案 »

  1.   

    double类型的0.0 != 0,这点一定要注意了,也就是说0.0不是0,可能是0.00000000000000001。所以不会出现异常。
    而0.0具体是多少,谁也不知道,是由虚拟机运行时在某一个误差范围内随即产生的。所以每次运行时候你得到的i的结果都不一样。任何语言都有明确的说明,对于float、double类型是不能使用==或!=等比较符号来比较两个数的大小的。
      

  2.   

    0.0/0.0 这个在浮点数中称 NaN,可以去看看 Double.NaN 或 Float.NaN 的 API DOC 说明。这个数有个特点就是 NaN != NaN 的
      

  3.   

    可以比较大小啊,给个特定的值是可以的,但是结果就是456了,只有0.0/0.0的时候是123,你说的虽然有道理,但是我还有一个问题,0.0/0.0虽然是不确定的,但是我只定义了1个i啊,这样i同时不是只指向1个内存地址嘛,为什么同一个i会不相等呢?
      

  4.   

    我看了Nan的原代码了    /** 
         * A constant holding a Not-a-Number (NaN) value of type
         * <code>double</code>. It is equivalent to the value returned by
         * <code>Double.longBitsToDouble(0x7ff8000000000000L)</code>.
         */
        public static final double NaN = 0.0d / 0.0;
    我的API上就是对这段话的解释,说他是Double.longBitsToDouble(0x7ff8000000000000L),你提到的那个特点NaN != NaN 我的API上没有,能把你看到的解释贴在下边吗?谢谢指点
      

  5.   

    IEEE 754-1985, 5.7
    http://754r.ucbtest.org/standards/754xml.htmlJava Language Specification,第 4.2.3、15.21.1 节
    http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3
    http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5198
      

  6.   

    节选自 Java Language Specification,第 15.21.1 节:If either operand is NaN, then the result of == is false but the result of != is true.
    Indeed, the test x!=x is true if and only if the value of x is NaN. (The methods
    Float.isNaN and Double.isNaN may also be used to test whether a value is NaN.)如果有一个操作数是 NaN,那么“==”的运算结果为 false,而“!=”的结果为 true。如果 x 的
    值为 NaN 时,x != x 的运算结果是 true。(使用 Float.isNaN 和 Double.isNaN 方法,可以测
    试某个值是否是 NaN。)
      

  7.   

    double类型的0.0 != 0有精度问题
      

  8.   

    一楼正解处理double和float可不能按常规思维去理解了。。