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


C++ hypot(), hypotf(), hypotl()用法及代碼示例

C++中的hypot()函數返回所傳遞的參數平方和的平方根。它找到斜邊,斜邊是直角三角形的最長邊。它由以下公式計算:

 h = sqrt(x2+y2)

其中x和y是三角形的另外兩個邊。

用法:
double hypot(double x, double y);
float hypot(float x, float y);
long double hypot(long double x, long double y);

例子:


Input:x=3, y=4
Output:5

Input:x=9, y=10
Output:13.4536

說明

頭文件:cmath
參數:hypot()采用2或3個整數或浮點型參數。
返回
1.如果傳遞了兩個參數,則為直角三角形的斜邊。
2.如果傳遞了三個參數,則從原點到(x,y,x)的距離

異常或錯誤
1. hypot(x,y),hypot(y,x)和hypot(x,-y)是等效的。
2.如果參數之一為0,則hypot(x,y)等效於使用非零參數調用的fab。3.如果參數之一為無限或未定義,hypot(x,y)返回未定義。

示例應用程序:給定另一邊的兩個邊,找到直角三角形的斜邊。

// CPP program to illustrate 
// hypot() function 
#include <cmath> 
#include <iostream> 
using namespace std; 
// Driver Program 
int main() 
{ 
    double x = 9, y = 10, res; 
    res = hypot(x, y); 
  
    // hypot() returns double in this case 
    cout << res << endl; 
    long double a, b, result; 
    a = 4.525252; 
    b = 5.767676; 
  
    // hypot() returns long double in this case 
    result = hypot(a, b); 
    cout << result; 
    return 0; 
}

輸出:

13.4536
7.33103

hypotf() function

hypotf()函數與hypot函數相同,唯一的區別是該函數的參數和返回類型為浮點型。附加到“ hypotf”後麵的“ f”字符表示float,它表示函數的參數類型和返回類型。

Syntax
float hypotf(float x);

hypotf()的C++程序實現
在此,為變量分配浮點類型,否則會發生類型不匹配錯誤。

// CPP program to illustrate 
// hypotf() function 
#include <cmath> 
#include <iostream> 
using namespace std; 
// Driver Program 
int main() 
{ 
    float x = 9.3425, y = 10.0987, res; 
  
    // hypotf() takes float values and returns float 
    res = hypotf(x, y); 
    cout << res << endl; 
    return 0; 
}

輸出:

13.7574

hypotl() function

hypotl()函數與hypot函數相同,唯一的區別是該函數的參數和返回類型為long double類型。附加在'hypotl'上的'l'字符表示long double,它表示參數類型和返回類型函數的

Syntax
long double hypotl(long double x);

hypotl()的C++程序實現
在此,為變量分配了long double類型,否則會發生類型不匹配錯誤。

// CPP program to illustrate 
// hypotl() function 
#include <cmath> 
#include <iostream> 
using namespace std; 
// Driver Program 
int main() 
{ 
    long double x = 9.3425453435, y = 10.0987456456, res; 
  
    // hypotl() takes long double values and returns long double 
    res = hypotl(x, y); 
    cout << res << endl; 
    return 0; 
}

輸出:

13.7575


相關用法


注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 hypot(), hypotf(), hypotl() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。