Java - Math nextAfter(float x, double y) 方法



描述

Java Math nextAfter(float start, double direction) 方法返回第一個引數在第二個引數方向上的相鄰浮點數。如果兩個引數比較相等,則返回等效於第二個引數的值。特殊情況:−

  • 如果任一引數為 NaN,則返回 NaN。

  • 如果兩個引數都是帶符號的零,則返回等效於 direction 的值。

  • 如果start 為 Float.MIN_VALUE,並且 direction 的值使得結果應該具有較小的幅度,則返回與 start 符號相同的零。

  • 如果start 為無窮大,並且 direction 的值使得結果應該具有較小的幅度,則返回與 start 符號相同的 Float.MAX_VALUE。

  • 如果start 等於 Float.MAX_VALUE,並且 direction 的值使得結果應該具有較大的幅度,則返回與 start 符號相同的無窮大。

宣告

以下是java.lang.Math.nextAfter() 方法的宣告

public static float nextAfter(float start, double direction)

引數

  • start − 起始浮點數

  • direction − 指示應返回 start 的哪個鄰居或 start 本身的值

返回值

此方法返回在 direction 方向上與 start 相鄰的浮點數。

異常

示例:獲取兩個正值的下一個值

以下示例演示了 Math nextAfter() 方法在兩個正值上的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two numbers
      float x = 98759.765f;
      double y = 154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:−

Math.nextAfter(98759.766,154.28764)=98759.76

示例:獲取一個正值和一個負值的下一個值

以下示例演示了 Math nextAfter() 方法在一個正值和一個負值上的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two numbers
      float x = -98759.765f;
      double y = 154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:−

Math.nextAfter(-98759.766,154.28764)=-98759.76

示例:獲取兩個負值的下一個值

以下示例演示了 Math nextAfter() 方法在負值上的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two numbers
      float x = -98759.765f;
      double y = -154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:−

Math.nextAfter(-98759.766,-154.28764)=-98759.76
java_lang_math.htm
廣告