0
我尝试这样做:NaN是否等于0?
int x = (int)Math.sqrt(-1); //Math.sqrt(-1) returns NaN
System.out.println(x);
并且输出是:
转换
NaN
为整数类型,或执行一个整数操作,其浮点数int等价物会产生NaN
,通常会引发异常。在Java中,这样的操作抛出的java.lang.ArithmeticException
实例,但我的代码运行正常,没有任何异常,且输出为0
。
有什么理由呢?
那么,为什么我的代码给出输出'0'? – Hackerdarshi
@Bathsheba虽然这回答了题目中的问题,但提供解释代码片断的行为方式会有所帮助。 – SarathChandra
@Hackerdarshi [这个问题是重复的问题](http://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in -java)涵盖了这一点。 – khelwood