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。很另人迷惑,希望高手指点。
而0.0具体是多少,谁也不知道,是由虚拟机运行时在某一个误差范围内随即产生的。所以每次运行时候你得到的i的结果都不一样。任何语言都有明确的说明,对于float、double类型是不能使用==或!=等比较符号来比较两个数的大小的。
* 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上没有,能把你看到的解释贴在下边吗?谢谢指点
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
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。)