编写程序,计算2个复数的和、差、积、商。 注意,Complex类的定义应该这样开始: class Complex { 也就是说,Complex类的class前面不要有public。
时间: 2024-05-07 09:16:30 浏览: 9
```
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 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 {
double denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
void display() const {
if (imag >= 0) {
cout << real << "+" << imag << "i" << endl;
} else {
cout << real << imag << "i" << endl;
}
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, -4);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex product = c1 * c2;
Complex quotient = c1 / c2;
cout << "Sum: ";
sum.display();
cout << "Difference: ";
diff.display();
cout << "Product: ";
product.display();
cout << "Quotient: ";
quotient.display();
return 0;
}
```