Java Math hypot() 方法
hypot()
方法的语法是:
Math.hypot(double x, double y)
注意:hypot()
方法是一个静态方法。因此,我们可以直接使用类名 Math
来调用该方法。
hypot() 方法的参数
- x, y - 双精度浮点数类型的参数
hypot() 方法的返回值
- 返回 Math.sqrt(x**2 + y**2)
返回值应该在 double
数据类型的范围内。
注意:Math.sqrt()
方法返回指定参数的平方根。要了解更多,请访问 Java Math.sqrt()。
示例 1:Java Math.hypot() 方法
class Main {
public static void main(String[] args) {
// 创建变量
double x = 4.0;
double y = 3.0;
// 计算 Math.hypot()
System.out.println(Math.hypot(x, y)); // 5.0
}
}
示例 2:使用 Math.hypot() 方法验证毕达哥拉斯定理
class Main {
public static void main(String[] args) {
// 三角形的两边
double side1 = 6.0;
double side2 = 8.0;
// 根据毕达哥拉斯定理
// 斜边 = (side1)2 + (side2)2
double hypotenuse1 = (side1) * (side1) + (side2) * (side2);
System.out.println(Math.sqrt(hypotenuse1)); // 输出 10.0
// 使用 Math.hypot() 计算斜边
// Math.hypot() 计算 √((side1)2 + (side2)2)
double hypotenuse2 = Math.hypot(side1, side2);
System.out.println(hypotenuse2); // 输出 10.0
}
}
在上面的示例中,我们使用了 Math.hypot()
方法和毕达哥拉斯定理来计算三角形的斜边。