Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน hypot(), hypotf(), hypotl() ใน C++

ฟังก์ชัน hypot()

ฟังก์ชันนี้ใช้สำหรับ คำนวณด้านตรงข้ามมุมฉาก (hypotenuse) ของสามเหลี่ยมมุมฉาก ฟังก์ชันนี้ส่งคืนค่ารากที่สองของผลรวมกำลังสองของตัวแปรสองตัว เป็นฟังก์ชันของไฟล์หัวข้อ <cmath>

ด้านตรงข้ามมุมฉาก (Hypotenuse) คืออะไร?

ด้านตรงข้ามมุมฉากคือด้านที่ยาวที่สุดของสามเหลี่ยมมุมฉาก สูตรคำนวณคือ:

H = √(x² + y²)

ไวยากรณ์ (Syntax)

double hypot(double x, double y);       // C++11
float hypot(float x, float y);          // C++11
long double hypot(long double x, long double y); // C++11
// รองรับ overload สำหรับสามพารามิเตอร์ (C++17): hypot(x, y, z) = √(x²+y²+z²)

พารามิเตอร์ (Parameters)

ฟังก์ชัน hypot() รับพารามิเตอร์สองตัว (หรือสามตัวใน C++17) คือ x และ y

ค่าที่ส่งคืน (Return Value)

ส่งคืนค่า √(x² + y²) คำนวณได้อย่างแม่นยำและหลีกเลี่ยงการล้น (overflow) หรือการลดระดับความแม่นยำ (underflow) ที่อาจเกิดขึ้นหากคำนวณด้วยตนเอง

ตัวอย่างการใช้งาน hypot()

// c++ program to demonstrate the working of hypot() function
#include <cmath>
#include <iostream>
using namespace std;

int main() {
    // กำหนดค่าเริ่มต้นสองตัวแปร
    double a = 3, b = 4, c;
    cout << "A = " << a << " B = " << b;
    // เรียกใช้ hypot()
    c = hypot(a, b);
    cout << "\nC = " << c << endl;
    double x = 12, y = 5, z;
    cout << "X = " << x << " Y = " << y;
    z = hypot(x, y);
    cout << "\nZ = " << z;
    return 0;
}

ผลลัพธ์ (Output)

A = 3 B = 4
C = 5
X = 12 Y = 5
Z = 13

ฟังก์ชัน hypotf()

hypotf() ทำงานเหมือน hypot() แต่ต่างตรงที่ hypotf() ส่งคืนชนิดข้อมูล float และพารามิเตอร์ก็เป็น float เช่นกัน เป็นฟังก์ชันของ <cmath>

ไวยากรณ์ (Syntax)

float hypotf(float x, float y);

ตัวอย่างการใช้งาน hypotf()

// c++ program to demonstrate the working of hypotf() function
#include <cmath>
#include <iostream>
using namespace std;

int main() {
    float x = 12.75f, y = 5.56f, z;
    cout << "X = " << x << " Y = " << y;
    z = hypotf(x, y);
    cout << "\nZ = " << z;
    return 0;
}

ผลลัพธ์ (Output)

X = 12.75 Y = 5.56
Z = 13.90956

ฟังก์ชัน hypotl()

hypotl() ทำงานเหมือน hypot() แต่ต่างตรงที่ hypotl() ส่งคืนชนิดข้อมูล long double และพารามิเตอร์ก็เป็น long double เช่นกัน เป็นฟังก์ชันของ <cmath>

ไวยากรณ์ (Syntax)

long double hypotl(long double x, long double y);

ตัวอย่างการใช้งาน hypotl()

// c++ program to demonstrate the working of hypotl() function
#include <cmath>
#include <iostream>
#include <iomanip> // สำหรับ setprecision
using namespace std;

int main() {
    long double x = 9.342553435L, y = 10.0987456456L, z;
    cout << "X = " << x << " Y = " << y;
    z = hypotl(x, y);
    cout << fixed << setprecision(10) << "\nZ = " << z;
    return 0;
}

ผลลัพธ์ (Output)

X = 9.3425534350 Y = 10.0987456456
Z = 13.7575000000

ข้อดีของ hypot()/hypotf()/hypotl(): คำนวณ √(x²+y²) ได้อย่างแม่นยำและปลอดภัยจากการล้น (overflow) และการลดระดับความแม่นยำ (underflow) มากกว่าการคำนวณด้วยตนเองด้วย sqrt(x*x + y*y)