當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。