2.7.2. hypot.cpp

Time: 00:02:48 | Download: Large, Large (CC), Small | Streaming, Streaming (CC)
Review
\[c = { \sqrt{a^2+b^2} }\] A picture of a right triangle - a triangle with one angle that is exactly 90 degrees. The two sides or legs adjacent to the 90-degree angle are labeled a and b. The side opposite the 90-degree angle, the hypotenuse, is labeled c.
The hypotenuse length of a right triangle. A right triangle has an interior angle of 90 degrees - a right angle. We typically label the two sides or legs adjacent to the right angle a and b, and the side opposite the right angle, the hypotenuse, c.

Test Cases

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

Caution

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

Program

#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;
}
hypot.cpp. The program prompts the user to enter the two side lengths and calculates and prints the hypotenuse length. Focus on the parentheses used on lines (a) and (b).
  1. The program squares a and b using self multiplication. Multiplication's precedence is higher than addition's, so parentheses are not needed around a*a and b*b. The parentheses in this statement form the argument list to the square-root function, sqrt. The program evaluates the expression inside the parentheses first, and the resulting value is passed or copied to sqrt. The function returns a value, the assignment saves it in c, and the next statement prints it.
  2. In this version, the program squares the lengths of the two sides with the pow function. All parentheses in the statement are function argument lists. The program evaluates the sub-expressions and operators in this order:
    1. pow(a, 2)
    2. pow(b, 2)
    3. pow(a, 2) + pow(b, 2)
    4. sqrt(pow(a, 2) + pow(b, 2))
    5. c = sqrt(pow(a, 2) + pow(b, 2))