📜  Java中的浮点 isNaN() 方法及示例

📅  最后修改于: 2022-05-13 01:55:23.366000             🧑  作者: Mango

Java中的浮点 isNaN() 方法及示例

Float 类中的Float.isNaN()方法是Java中的内置方法,如果此 Float 值或指定的浮点值是非数字 (NaN),则返回 true,否则返回 false。

语法

public boolean isNaN()
        or
public static boolean isNaN(float val)

参数:该函数接受单个参数val ,该参数指定在将 Float 类作为静态方法直接调用时要检查的值。方法作为实例方法时不需要该参数。

返回值:如果 val 为NaN则返回true ,否则返回false

下面的程序说明了Java中的isNaN()方法:

程序 1:使用静态 isNaN() 方法

// Java code to demonstrate
// Float isNaN() method
// without parameter
  
class GFG {
    public static void main(String[] args)
    {
  
        // first example
        Float f1 = new Float(1.0 / 0.0);
  
        boolean res = f1.isNaN();
  
        // printing the output
        if (res)
            System.out.println(f1 + " is NaN");
        else
            System.out.println(f1 + " is not NaN");
  
        // second example
        f1 = new Float(0.0 / 0.0);
  
        res = f1.isNaN();
  
        // printing the output
        if (res)
            System.out.println(f1 + " is NaN");
        else
            System.out.println(f1 + " is not NaN");
    }
}
输出:
Infinity is not NaN
NaN is NaN

程序 2:使用非静态 isNaN() 方法

// Java code to demonstrate
// Float isNaN() method
// with parameter
  
class GFG {
    public static void main(String[] args)
    {
  
        // first example
        Float f1 = new Float(1.0 / 0.0);
  
        boolean res = f1.isNaN(f1);
  
        // printing the output
        if (res)
            System.out.println(f1 + " is NaN");
        else
            System.out.println(f1 + " is not NaN");
  
        // second example
        f1 = new Float(0.0 / 0.0);
  
        res = f1.isNaN(f1);
  
        // printing the output
        if (res)
            System.out.println(f1 + " is NaN");
        else
            System.out.println(f1 + " is not NaN");
    }
}
输出:
Infinity is not NaN
NaN is NaN

参考: https: Java/lang/Float.html#isNaN()