在C++中,complex是一個模板類,用于表示復數。它定義在
以下是complex類的使用方法示例:
#include <iostream>
#include <complex>
int main() {
// 創建復數對象
std::complex<double> z1(3.0, 4.0); // 3 + 4i
std::complex<double> z2(-2.0, 1.0); // -2 + i
// 訪問實部和虛部
std::cout << "Real part of z1: " << z1.real() << std::endl;
std::cout << "Imaginary part of z1: " << z1.imag() << std::endl;
// 加法、減法、乘法、除法
std::complex<double> sum = z1 + z2;
std::complex<double> diff = z1 - z2;
std::complex<double> prod = z1 * z2;
std::complex<double> quot = z1 / z2;
// 打印結果
std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << diff << std::endl;
std::cout << "Product: " << prod << std::endl;
std::cout << "Quotient: " << quot << std::endl;
return 0;
}
上面的示例演示了如何創建complex對象,訪問實部和虛部,以及進行加法、減法、乘法和除法操作。您可以根據需要使用不同的數據類型(如float、double等)來創建complex對象。