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

sqrt, sqrtl, sqrtf ใน C++: ความแตกต่างและการใช้งาน

ใน <cmath> มีฟังก์ชัน Square Root 3 รูปแบบ สำหรับชนิดข้อมูลต่างกัน

1. sqrt() - Double Precision

double sqrt(double x);

มาตรฐาน ใช้กับ double ความแม่นยำ ~15-17 หลัก

ตัวอย่าง

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

int main() {
    double x = 144.0, y = 180.0;
    cout << fixed << setprecision(12);
    cout << sqrt(x) << endl; // 12.000000000000
    cout << sqrt(y) << endl; // 13.416407864999
}

2. sqrtf() - Single Precision (float)

float sqrtf(float x);

ใช้กับ float ความแม่นยำ ~6-9 หลัก เร็วกว่า บนบาง Hardware

ตัวอย่าง

float x = 144.0f, y = 180.0f;
cout << fixed << setprecision(6);
cout << sqrtf(x) << endl; // 12.000000
cout << sqrtf(y) << endl; // 13.416408

3. sqrtl() - Extended Precision (long double)

long double sqrtl(long double x);

ใช้กับ long double ความแม่นยำสูงสุด (บน x86: 80-bit extended precision)

เหมาะกับจำนวนเต็มใหญ่ (10¹⁸)

ตัวอย่าง

long long x = 5000000000000000000LL;
long long y = 999999999999999999LL;
cout << fixed << setprecision(12);
cout << sqrtl(x) << endl; // 2236067977.499789696420
cout << sqrtl(y) << endl; // 999999999.999999999476

สรุปการเลือกใช้

FunctionTypePrecisionUse Case
sqrtffloat~7 digitsEmbedded, GPU, Memory critical
sqrtdouble~15 digitsGeneral purpose (Default)
sqrtllong double~18+ digitsHigh precision, Large integers

หมายเหตุ

  • Input ติดลบ → คืนค่า NaN (Not a Number)
  • C++17: std::sqrt Overload รองรับทุกชนิดอัตโนมัติ
  • Performance: sqrtf < sqrt < sqrtl (โดยทั่วไป)