hypot()
方法的语法是
Math.hypot(double x, double y)
注意:hypot()
方法是一个 静态方法。因此,我们可以直接使用类名 Math
来调用该方法。
hypot() 参数
- x, y - double 类型参数
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()
方法和 勾股定理 来计算三角形的斜边。