在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对象。