c++复数的四则运算计算器
时间: 2023-10-04 21:08:47 浏览: 109
以下是一个简单的C++复数四则运算计算器的示例代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
private:
double real, 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 r = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / r, (imag * c.real - real * c.imag) / r);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
if (c.imag >= 0) os << c.real << " + " << c.imag << "i";
else os << c.real << " - " << abs(c.imag) << "i";
return os;
}
};
int main() {
Complex a(1, 2);
Complex b(3, -4);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a / b = " << a / b << endl;
return 0;
}
```
在这个示例代码中,我们定义了一个名为Complex的类,它包含了复数的实部和虚部。我们还重载了加、减、乘、除和插入运算符,以便我们可以对两个复数进行四则运算并将结果输出到标准输出流中。
在主函数中,我们声明了两个复数a和b,并对它们进行了加、减、乘、除运算,并将结果输出到控制台。
阅读全文