Exercise 4
The Pythagorean theorem states that for a right triangle, the relationship between the length of the hypotenuse \( c \) and the lengths of the other sides \( a \) and \( b \) is given by:
\[c^2 = a^2 + b^2\]
Write a script that will prompt the user for the lengths \( a \) and \( c \), call a function findb to calculate and return the length of \( b \), and print the result. Note that any values of \( a \) or \( c \) that are less than or equal to zero would not make sense, so the script should print an error message if the user enters any invalid value.
Right Triangle Diagram:
Hypotenuse (c) is the longest side, opposite the right angle
Sides a and b form the right angle
Hypotenuse (c) is the longest side, opposite the right angle
Sides a and b form the right angle
Provided Function: findb.m
function b = findb(a,c)
% Calculates b from a and c
b = sqrt(c^2 - a^2);
end
% Calculates b from a and c
b = sqrt(c^2 - a^2);
end
Script Requirements:
- Prompt user for input values of
aandc - Validate that both inputs are positive numbers
- Call the
findbfunction to calculateb - Display the calculated value of
b - Include error handling for invalid inputs
Input Validation Rules:
a > 0(must be positive)c > 0(must be positive)c > a(hypotenuse must be longer than side a)c² ≥ a²(to avoid imaginary numbers)
Expected Program Flow:
- Prompt for side
a - If
a ≤ 0, display error and exit - Prompt for hypotenuse
c - If
c ≤ 0, display error and exit - If
c ≤ a, display error and exit - Calculate
b = findb(a, c) - Display result:
"The length of side b is X"
Mathematical Rearrangement:
From the Pythagorean theorem: c² = a² + b²
Solving for b: b² = c² - a²
Therefore: b = √(c² - a²)
To take full advantage, try implementing the exercise before checking the solutions!