复数由实部与虚部两部分组成,如:3+2i。假设复数的实况与虚部都是double类型。两个复数可以进行相加、减、乘运算。可以按:3.2+2.6i或3.2-1.5i或0.5i或1.5格式转换成字符串格式。 复数是一个常对象,即:进行运算时
时间: 2024-05-15 19:13:45 浏览: 197
复数的运算
4星 · 用户满意度95%
不会改变原有的复数对象,而是返回一个新的复数对象。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
std::string to_string() const {
if (imag >= 0) {
return std::to_string(real) + "+" + std::to_string(imag) + "i";
} else {
return std::to_string(real) + std::to_string(imag) + "i";
}
}
};
int main() {
Complex c1(3.2, 2.6);
Complex c2(1.5, -0.5);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex prod = c1 * c2;
std::cout << "Sum: " << sum.to_string() << std::endl;
std::cout << "Difference: " << diff.to_string() << std::endl;
std::cout << "Product: " << prod.to_string() << std::endl;
return 0;
}
```
输出结果为:
```
Sum: 4.7+2.1i
Difference: 1.7+3.1i
Product: 6.95+2.3i
```
阅读全文