How to compute the hypotenuse h of the triangle in Java

1 Answer

0 votes
public class HypotenuseCalculator {
    public static void main(String[] args) {
        // Legs of the triangle
        double a = 7;
        double b = 5;

        // Method 1: Using Math.sqrt and Math.pow
        double h1 = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
        System.out.printf("The hypotenuse (h) is: %.6f%n", h1);
        
        // Method 2: Using Math.sqrt
        double h2 = Math.sqrt(a * a + b * b);
        System.out.printf("The hypotenuse (h) is: %.6f%n", h2);

        // Method 3: Using Math.hypot 
        double h3 = Math.hypot(a, b);
        System.out.printf("The hypotenuse (h) is: %.6f%n", h3);
    }
}



/*
run:

The hypotenuse (h) is: 8.602325
The hypotenuse (h) is: 8.602325
The hypotenuse (h) is: 8.602325

*/

 



answered Jun 28, 2025 by avibootz
edited Jun 28, 2025 by avibootz
...