请写一个能键盘输入数据进行复数的加减乘除乘方立方运算的C++代码
时间: 2023-06-14 08:06:59 浏览: 100
C++实现复数的加减乘除运算
以下是一个简单的C++代码,用于进行复数的加减乘除乘方立方等运算:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
public:
double real, imag; // 实部和虚部
Complex(double r = 0, double i = 0) : 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);
}
Complex operator/(const Complex& other) const {
double den = other.real * other.real + other.imag * other.imag;
return Complex((real * other.real + imag * other.imag) / den, (imag * other.real - real * other.imag) / den);
}
Complex operator^(int n) const {
double r = pow(sqrt(real * real + imag * imag), n);
double t = atan2(imag, real);
return Complex(r * cos(n * t), r * sin(n * t));
}
Complex operator~() const {
return Complex(real, -imag);
}
friend Complex operator*(double a, const Complex& b) {
return Complex(a * b.real, a * b.imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
friend istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
};
int main() {
Complex a, b;
char op;
cout << "Enter the first complex number: ";
cin >> a;
cout << "Enter the second complex number: ";
cin >> b;
cout << "Enter the operator (+, -, *, /, ^, ~): ";
cin >> op;
switch (op) {
case '+':
cout << a + b << endl;
break;
case '-':
cout << a - b << endl;
break;
case '*':
cout << a * b << endl;
break;
case '/':
cout << a / b << endl;
break;
case '^':
int n;
cout << "Enter the power (integer): ";
cin >> n;
cout << (a ^ n) << endl;
cout << (b ^ n) << endl;
break;
case '~':
cout << ~a << endl;
cout << ~b << endl;
break;
default:
cout << "Invalid operator." << endl;
break;
}
return 0;
}
```
该程序需要用户输入两个复数以及运算符,然后输出计算结果。用户可以进行加法、减法、乘法、除法、乘方和共轭运算。
阅读全文