Java Math hypot()方法計算x2 + y2的平方根(即,斜邊)并將其返回。
hypot()方法的語法為:
Math.hypot(double x, double y)
注意:hypot()方法是靜態(tài)方法。因此,我們可以使用類名Math直接調(diào)用該方法。
x,y - 雙精度類型參數(shù)
返回Math.sqrt(x 2 + y 2)
返回的值應在double數(shù)據(jù)類型的范圍內(nèi)。
注意:Math.sqrt()方法返回指定參數(shù)的平方根。要了解更多信息,請訪問Java Math.sqrt()。
class Main { public static void main(String[] args) { //創(chuàng)建變量 double x = 4.0; double y = 3.0; //計算 Math.hypot() System.out.println(Math.hypot(x, y)); // 5.0 } }
class Main { public static void main(String[] args) { //三角形的邊 double side1 = 6.0; double side2 = 8.0; //根據(jù)畢達哥拉斯定理 // hypotenuse = (side1)2 + (side2)2 double hypotenuse1 = (side1) *(side1) + (side2) * (side2); System.out.println(Math.sqrt(hypotenuse1)); // 返回 10.0 // 斜邊計算使用 Math.hypot() // Math.hypot() gives √((side1)2 + (side2)2) double hypotenuse2 = Math.hypot(side1, side2); System.out.println(hypotenuse2); // 返回 10.0 } }
在上面的示例中,我們使用的Math.hypot()方法和畢達哥拉斯定理來計算三角形的斜邊。