你能猜出以下代码片段的输出吗
public class Test { public static void main(String[] args) { System.out.println( 2 % 0 ); } } |
是的,你猜对了:算术例外 输出:
Exception in thread "main" java.lang.ArithmeticException: / by zero at traps.Test.main(Test.java:3)
现在猜猜下面的输出:
public class Test { public static void main(String[] args) { System.out.println( 2.0 % 0 ); } } |
你猜对了吗? 输出:
NaN
南是什么?
“ 楠 代表“不是数字”。如果浮点运算的某些输入参数导致运算产生某些未定义的结果,则会生成“Nan”。例如 0.0除以0.0 是算术上未定义的。找出原因 负数的平方根 也没有定义。
//Java Program to illustrate NaN public class Test { public static void main(String[] args) { System.out.println( 2.0 % 0 ); System.out.println( 0.0 / 0 ); System.out.println(Math.sqrt(- 1 )); } } |
输出:
NaN NaN NaN
在javadoc中,常量字段NaN分别在Float和Double类中声明如下。
public static final float NaN = 0f / 0f; public static final double NaN = 0d / 0d;
如何比较NaN值?
所有以NaN为操作数的数值运算都会产生NaN。这背后的原因是NaN是无序的,因此涉及一个或两个NaN的数值比较操作返回false。
- 如果其中一个或两个操作数均为NaN,则数值比较运算符和>=始终返回false。( §15.20.1 )
- 如果任一操作数为NaN,则相等运算符==返回false。
- 不等式算子!=如果任一操作数为NaN,则返回true。( §15.21.1 )
// Java program to test relational operator on NaN public class ComparingNaN { public static void main(String[] args) { // comparing NaN constant field defined in // Float Class System.out.print( "Check if equal :" ); System.out.println(Float.NaN == Float.NaN); System.out.print( "Check if UNequal: " ); System.out.println(Float.NaN != Float.NaN); // comparing NaN constant field defined in Double Class System.out.print( "Check if equal: " ); System.out.println(Double.NaN == Double.NaN); System.out.print( "Check if UNequal: " ); System.out.println(Double.NaN != Double.NaN); // More Examples double NaN = 2.1 % 0 ; System.out.println(( 2.1 % 0 ) == NaN); System.out.println(NaN == NaN); } } |
输出:
Check if equal :false Check if UNequal: true Check if equal: false Check if UNequal: true false false
isNaN()方法
如果此对象表示的值为NaN,则此方法返回true;否则就错了。
import java.lang.*; public class isNan { public static void main(String[] args) { Double x = new Double(- 2.0 / 0.0 ); Double y = new Double( 0.0 / 0.0 ); // returns false if this Double value is not a Not-a-Number (NaN) System.out.println(y + " = " + y.isNaN()); // returns true if this Double value is a Not-a-Number (NaN) System.out.println(x + " = " + x.isNaN()); } } |
输出:
NaN = true -Infinity = false
浮点类型在使用数学值操作时不会产生异常
IEEE 754 浮点数可以表示正无穷大或负无穷大,也可以表示NaN(不是数字)。这三个值来自计算结果未定义或无法准确表示的结果。 Java遵循已知的数学事实。1.0/0.0是无穷大,但其他是不确定形式,Java将其表示为NaN(不是数字)。
// Java program to illustrate output of floating // point number operations public class Test { public static void main(String[] args) { System.out.println( 2.0 / 0 ); System.out.println(- 2.0 / 0 ); System.out.println( 9 .0E234 / 0 .1E- 234 ); } } |
输出:
Infinity -Infinity Infinity
参考资料: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html
本文由 潘卡吉·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。