Question:
Write a function hypotenuse that calculates the length of the hypotenuse of a right triangle. The length of the two legs is passed to the function. Tip: In a right triangle the Pythagorean theorem is valid. If a and b are the lengths of the two legs and c is the length of the hypotenuse, the following is true: a² + b² = c². Since 3² + 4² = 5² applies, hypotenuse(3, 4) should return 5.
Answer:
function hypotenuse (a, b) {
let s = a**2 + b**2;
let h = Math.sqrt(s);
return h;
};
or
function hypotenuse (a,b) {
let firstLength = Math.pow(a,2);
let secondLength = Math.pow(b,2);
let thirdLength = firstLength + secondLength;
let xyz = Math.sqrt(thirdLength);
return xyz;
};
> Pythagorean Theorem: a² + b² = c²
> in the first example we use the exponentiation operator (**) which raises the first operand to the power of the second operand and declare it to variable 's'
> we then use the Math.sqrt method on the variable 's' to return the square root of a number and declare it to variable 'h'
> in the second example we declare two different variables (firstLength & secondLength) for the lengths and initialize the values we get by using the Math.pow method
> we then declare a third variable that adds both the variables (firstLength + secondLength)
> we then use the Math.sqrt method on the variable 'thirdLength' to return the square root and declare it to variable 'xyz'
> in the end we return xyz
No comments:
Post a Comment