\[c = { \sqrt{a^2+b^2} }\] | ![]() |
The well-known property of right triangles, that the side lengths form the ratio 3:4:5, provides our first test case. (Some researchers speculate that the Egyptians used this ratio to help build the ancient pyramids without using modern surveying tools.) We could use the ratio to generate other test cases (e.g., 9:12:15), but it's best to have a different, more general test case. So, pick two arbitrary values for the legs and use a calculator to calculate the hypotenuse, creating a second test case.
a | b | c | |
---|---|---|---|
Case 1 | 3 | 4 | 5 | Case 2 | 4.5 | 6.25 | 7.70146 |
Mathematically and programmatically, taking the square root of a negative value is an illegal operation. But this problem will never occur with the following program because it squares both a and b, yielding non-negative values. If the sqrt function argument is negative, the returned (and printed) value looks rather strange and indicates an error condition: -1.#IND
#include <iostream> #include <cmath> using namespace std; int main() { double a; cout << "Please enter side a: "; cin >> a; cout << "Please enter side b: "; double b; cin >> b; double c = sqrt(a*a + b*b); // (a) //double c = sqrt(pow(a, 2) + pow(b, 2)); // (b) cout << c << endl; return 0; }