English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of hypot() function

C++ Library Function <cmath>

C ++The hypot() function in the returned parameter returns the square root of the sum of the squares of the passed parameters (based on the Pythagorean theorem).

hypot() prototype

double hypot(double x, double y);
float hypot(float x, float y);
long double hypot(long double x, long double y);
Promoted pow(Type1 x, Type2 y);
double hypot(double x, double y, double x); //(from C++17 begin)
float hypot(float x, float y, float z); // (from C++17 begin)
long double hypot(long double x, long double y, long double z); // (from C++17 begin)
Promoted pow(Type1 x, Type2 y, Type2 y); //(from C++17 begin)

from C ++ 11Starting from C, if the parameters passed to hypot() are of type long double, the returned type is promoted to long double. If not, the returned type is promoted to double.

h = √(x2+y2

is mathematically equivalent to

h = hypot(x, y);

in C ++programming.

If three parameters are passed:

h = √(x2+y2+z2))

is mathematically equivalent to

h = hypot(x, y);

in C ++programming.

This function is used in<cmath>defined in the header file.

hypot() parameters

hypot() can be used2or3an integer or floating-point type parameter.

hypot() return value

hypot() returns:

  • If two parameters are passed, it is the hypotenuse of a right triangle, i.e., √(x^2 + y^2)2+y2)

  • If three parameters are passed, it is the distance from the origin to (x, y, z). √(x^2 + y^2 + z^2)2+y2+z2)

Example1:How hypot() works in C ++How does it work in C?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double x = 2.1, y = 3.1, result;
	result = hypot(x, y);
	cout << "hypot(x, y) = " << result << endl;
	long double yLD, resultLD;
	x = 3.52;
	yLD = 5.232342323;
	// In this example, the function returns long double
	resultLD = hypot(x, yLD);
	cout << "hypot(x, yLD) = " << resultLD;
	return 0;
{}

When running the program, the output is:

hypot(x, y) = 3.74433
hypot(x, yLD) = 6.30617

Example2:A function with three parameters, hypot()

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double x = 2.1, y = 3.1, z = 23.3, result;
	result = hypot(x, y, z);
	cout << "hypot(x, y, z) = " << result << endl;
	return 0;
{}

Note:This program is only supported by C ++ 17compiled with the new compiler.

C++ Library Function <cmath>