#include <iostream>
#include <cmath>
using namespace std;
class Complex {
public:
double real, imag; // 实部和虚部都是实数范围
Complex(double r = 0.0, double i = 0.0) {
real = r;
imag = i;
}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) const {
return *this * (c.conjugate()); // 注意要先求共轭再相乘,否则会出现除以零的情况
}
Complex operator^(int n) const {
Complex result(*this);
for (int i = 0; i < n; i++) result = result * result; // 实现幂次方运算
return result;
}
Complex operator%(const double p) const { // 实现取模运算
return *this * (Complex(1.0, 0.0) % p); // 先求出模长p的共轭复数,再与当前复数相乘即可得到模余数
}
double arg() const { // 实现辐角运算
return atan2(imag, real); // 采用反正切函数计算辐角,注意要使用复数的辐角定义,即π/2表示实轴的反向延长线与复平面的交点处的角度。
}
Complex conjugate() const { // 实现共轭运算
return Complex(real, -imag); // 直接将实部和虚部取相反数即可得到共轭复数。
}
};
int main() {
int choice;
double num1, num2;
cin >> choice >> num1 >> num2;
if (choice == 1) { // 如果是加法操作,则直接输出结果并返回。
Complex result = Complex(num1, num2);
cout << result << " + " << num1 << "i + " << num2 << "i = " << result + num1 << " + " << num2 << "i" << endl;
return 0;
} else if (choice == 2) { // 如果是减法操作,则先求出共轭复数,然后再进行减法运算。注意要先求出共轭复数再相减。
Complex a, b, c;
cin >> a >> b;
c = a + b;
c = c.conjugate(); // 先求出共轭复数c'=a+bi的共轭复数c'=(a-bi)。然后再用c'减去b即可得到结果c=a-bi。注意这里不能直接用c-b,因为两个复数相减时需要先进行共轭操作。
【无标题】
最新推荐文章于 2025-05-03 15:17:35 发布