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


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

C++ hypot() 函數

hypot() 函數是 cmath 頭文件的庫函數,用於求給定數字的斜邊,它接受兩個數字並返回斜邊的計算結果,即sqrt(x*x + y*y)

hypot() 函數的語法:

    hypot(x, y);

參數: x, y– 要計算斜邊的數字(或sqrt(x*x + y*y))

返回值: double– 它返回作為表達式結果的雙精度值sqrt(x*x + y*y)

例:

    Input:
    float x = 10.23;
    float y = 2.3;

    Function call:
    hypot(x, y);

    Output:
    10.4854

C++代碼演示hypot()函數的例子

// C++ code to demonstrate the example of 
// hypot() function

#include <iostream>
#include <cmath>
using namespace std;

// main code section
int main()
{
    float x = 10.23;
    float y = 2.3;

    // calculate the hypotenuse 
    float result = hypot(x, y);
    cout<<"hypotenuse of "<<x<<" and "<<y<<" is = "<<result;
    cout<<endl;
    
    //using sqrt() function
    result = sqrt((x*x + y*y));
    cout<<"hypotenuse of "<<x<<" and "<<y<<" is = "<<result;
    cout<<endl;
    
    return 0;
}

輸出

hypotenuse of 10.23 and 2.3 is = 10.4854
hypotenuse of 10.23 and 2.3 is = 10.4854


相關用法


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