当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ hypot()用法及代码示例


C++ 中的hypot() 函数返回传递的参数平方和的平方根。

hypot()原型

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); // (since C++17)
float hypot(float x, float y, float z); // (since C++17)
long double hypot(long double x, long double y, long double z); // (since C++17)
Promoted pow(Type1 x, Type2 y, Type2 y); // (since C++17)

从 C++11 开始,如果传递给 hypot() 的任何参数是 long double ,则返回类型 Promotedlong double 。如果不是,则返回类型 Promoteddouble

h = √(x2+y2

在数学上相当于

h = hypot(x, y);

在 C++ 编程中。

如果传递了三个参数:

h = √(x2+y2+z2))

在数学上相当于

h = hypot(x, y);

在 C++ 编程中。

该函数在<cmath> 头文件中定义。

参数:

hytpot() 采用 2 或 3 个整数或浮点类型的参数。

返回:

hypot() 返回:

  • 如果传递了两个参数,则直角三角形的斜边,即。 e. √(x2+y2)
  • 如果传递了三个参数,即 √(x2+y2+z2) ,则从原点到 (x, y, x) 的距离。

示例 1:hypot() 如何在 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;
	
	// hypot() returns long double in this case
	resultLD = hypot(x, yLD);
	cout << "hypot(x, yLD) = " << resultLD;
	
	return 0;
}

运行程序时,输出将是:

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

示例 2:带有三个参数的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;
}

注意:该程序只能在支持 C++17 的新编译器中运行。

相关用法


注:本文由纯净天空筛选整理自 C++ hypot()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。