當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Math hypot()用法及代碼示例

Java Math hypot() 方法計算 x2 + y2 的平方根(即斜邊)並返回它。

用法:

Math.hypot(double x, double y)

注意: 這hypot()方法是靜態方法。因此,我們可以直接使用類名調用該方法Math.

參數:

  • x, y- 雙類型參數

hypot() 返回值

  • 返回數學.sqrt(x2+ 是2)

返回值應在double 數據類型的範圍內。

注意: 這Math.sqrt()方法返回指定參數的平方根。要了解更多信息,請訪問Math sqrt.

示例 1:Java 數學。hypot()

class Main {
  public static void main(String[] args) {

    // create variables
    double x = 4.0;
    double y = 3.0;

    //compute Math.hypot()
    System.out.println(Math.hypot(x, y));  // 5.0

  }
}

示例 2:使用數學的畢達哥拉斯定理。hypot()

class Main {
  public static void main(String[] args) {

    // sides of triangle
    double  side1 = 6.0;
    double side2 = 8.0;

    // According to Pythagoras Theorem
    // hypotenuse = (side1)2 + (side2)2
    double hypotenuse1 = (side1) *(side1) + (side2) * (side2);
    System.out.println(Math.sqrt(hypotenuse1));    // prints 10.0

    // Compute Hypotenuse using Math.hypot()
    // Math.hypot() gives √((side1)2 + (side2)2)
    double hypotenuse2 = Math.hypot(side1, side2);
    System.out.println(hypotenuse2);               // prints 10.0

  }
}

在上麵的示例中,我們使用了Math.hypot() 方法和Pythagoras Theorem 來計算三角形的斜邊。

相關用法


注:本文由純淨天空篩選整理自 Java Math hypot()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。