求解 C++ 中複數的 abs() 函式?
C++ 中的 abs 函式用於求解複數的絕對值。複數的絕對值(也稱為模)是複平面中複數到原點的距離。計算方法為
對於複數 a+bi
mod|a+bi| = √(a2+b2)
abs() 函式會在 C++ 中返回以上運算的結果。它在 complex 庫中定義,在使用前需要包含該庫。
使用 C++ 中複數的 abs() 函式的示例程式
#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
廣告