Java教程

Java Math hypot()

Java Math hypot()

Java Math hypot() 方法计算 x2 + y2(即斜边)的平方根并返回。
hypot() 方法的语法是:
Math.hypot(double x, double y)
注意: hypot() 方法是一个静态方法。因此,我们可以使用类名 Math 直接调用该方法。

hypot() 参数

x, y-双类型参数

hypot() 返回值

返回Math.sqrt(x2 + y2)
返回值应在 double数据类型范围内。
注意: Math.sqrt() 方法返回指定参数的平方根。要了解更多信息,请访问 Java Math.sqrt()。

示例 1: Java Math.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: 使用 Math.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() 方法和 毕达哥拉斯定理 来计算三角形的斜边。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4