ฟังก์ชัน abs ใน C++ ใช้หาค่าสัมบูรณ์ (absolute value) ของจำนวนเชิงซ้อน ค่าสัมบูรณ์ของจำนวนเชิงซ้อน (หรือเรียกว่า modulus) คือ ระยะทางของจำนวนนั้นจากจุดกำเนิดในมุมเชิงซ้อน สามารถหาได้โดยสูตร −
สำหรับจำนวนเชิงซ้อน a+bi:
mod|a+bi| = √(a2+b2)
ฟังก์ชัน abs() คืนค่าผลลัพธ์ของการคำนวณข้างต้นใน C++ ถูกนิยามในไลบรารี complex ที่ต้อง include เข้ามา
โปรแกรมแสดงการใช้งานฟังก์ชัน abs() สำหรับจำนวนเชิงซ้อนใน C++
#include <iostream>
#include <complex>
using namespace std;
int main() {
float a = 13.0, b = 5.0;
complex<double> complexnumber(a, b);
cout << "The absolute value of " << a << "+" << b << "i" << " is: ";
cout << abs(complexnumber) << endl;
return 0;
}
ผลลัพธ์
The absolute value of 13+5i is: 13.9284