C++使用面向对象程序设计方法编写一个计算器,实现对复数类型数据进行加、减、乘、除、平方和立方
时间: 2023-11-10 20:05:24 浏览: 81
下面是一个简单的C++计算器类,支持复数类型数据的加、减、乘、除、平方和立方运算:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
public:
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 {
double denominator = c.real * c.real + c.imag * c.imag;
if (denominator == 0) {
cerr << "Error: division by zero!" << endl;
return Complex();
}
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
Complex operator ^(int n) const {
double r = pow(sqrt(real * real + imag * imag), n);
double theta = atan2(imag, real);
return Complex(r * cos(n * theta), r * sin(n * theta));
}
friend ostream& operator <<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
private:
double real;
double imag;
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
Complex c4 = c1 - c2;
cout << "c1 - c2 = " << c4 << endl;
Complex c5 = c1 * c2;
cout << "c1 * c2 = " << c5 << endl;
Complex c6 = c1 / c2;
cout << "c1 / c2 = " << c6 << endl;
Complex c7 = c1 ^ 2;
cout << "c1 ^ 2 = " << c7 << endl;
Complex c8 = c2 ^ 3;
cout << "c2 ^ 3 = " << c8 << endl;
return 0;
}
```
使用示例:
```
c1 = 1 + 2i
c2 = 3 + 4i
c1 + c2 = 4 + 6i
c1 - c2 = -2 - 2i
c1 * c2 = -5 + 10i
c1 / c2 = 0.44 - 0.08i
c1 ^ 2 = -3 + 4i
c2 ^ 3 = -117 + 44i
```
阅读全文