#include <iostream>
#include <cstdlib>
#include <limits>
#include <iomanip>
#include <cmath>
using namespace std;
class MyComplex//2. 创建一个类 MyComplex,用来表示复数。
{
public:
MyComplex()
{}
MyComplex(double a, double b):real(a),imag(b)
{}
friend ostream& operator <<(ostream& os, const MyComplex& z);
friend istream& operator >> (istream& is, MyComplex& z);
MyComplex operator+(const MyComplex &z);
MyComplex operator-(const MyComplex &z);
MyComplex operator*(const MyComplex &z);
MyComplex operator/(const MyComplex &z);
private:
double real;
double imag;
};
ostream & operator<<(ostream & os, const MyComplex & z)
{
os.unsetf(std::ios::showpos);
os << "(" << z.real;
os.setf(std::ios::showpos);
os << z.imag << "i)";
return os;
}
istream & operator >> (istream & is, MyComplex & z)
{
// TODO: 在此处插入 return 语句
is >> z.real >> z.imag;
return is;
}
MyComplex MyComplex::operator+(const MyComplex & z)
{
return MyComplex(real + z.real, imag + z.imag);
}
MyComplex MyComplex::operator-(const MyComplex & z)
{
return MyComplex(real - z.real, imag - z.imag);
}
MyComplex MyComplex::operator*(const MyComplex & z)
{
return MyComplex(real * z.real - imag * z.imag, z.real * imag + z.imag * real);
}
MyComplex MyComplex::operator/(const MyComplex & z)
{
if (pow(z.real, 2) + pow(z.imag, 2) == 0)
{
cout << "Divisor can not be 0";
exit(0);
}
return MyComplex((real * z.real + imag * z.imag) / (pow(z.real, 2) + pow(z.imag, 2)), (imag * z.real - real * z.imag) / (pow(z.real, 2) + pow(z.imag, 2)));
}
int main() {
MyComplex z1, z2;
cin >> z1;
cin >> z2;
cout << "z1 + z2 = " << z1 + z2 << endl;
cout << "z1 - z2 + z1 = " << z1 - z2 + z1 << endl;
cout << "z1 * z2 - z1 = " << z1 * z2 - z1 << endl;
cout << "z1 / z2 + z1 = " << z1 / z2 + z1 << endl;
cout << "z2 - z1 / z1 = " << z2 - z1 / z1;
// GCC及VC编译器在调试模式下会暂停,便于查看运行结果
#if ( defined(__DEBUG__) || defined(_DEBUG) )
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
#endif
return 0;
}