复数四则

Posted on 2019-07-08 17:54  金色的省略号  阅读(173)  评论(0编辑  收藏  举报
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <limits>
 4 using namespace std;
 5 
 6 class MyComplex{
 7 public:
 8     double a;
 9     double b;
10 public:
11     MyComplex(double a = 0.0, double b = 0.0){
12         this->a = a;
13         this->b = b;
14     }
15     MyComplex& operator+(const MyComplex & c);
16     MyComplex& operator-(const MyComplex & c);
17     MyComplex& operator*(const MyComplex & c);
18     MyComplex& operator/ (const MyComplex &c);
19     
20     friend ostream& operator<<(ostream &stream, MyComplex& mc);
21     friend istream& operator>>(istream &stream, MyComplex& mc);
22 };
23 
24 
25 MyComplex& MyComplex::operator+(const MyComplex & c)
26 {
27     
28     this->a=a+c.a;
29     this->b=b+c.b;
30     return (*this);
31 }
32 
33 MyComplex& MyComplex::operator-(const MyComplex & c)
34 {
35     this->a=this->a-c.a;
36     this->b=this->b-c.b;
37     return (*this);
38 }
39 
40 MyComplex& MyComplex::operator*(const MyComplex & c)
41 {
42     this->a=a*c.a-b*c.b;
43     this->b=a*c.b+b*c.a;
44     return (*this);
45 }
46 
47 MyComplex& MyComplex::operator/ (const MyComplex &c) {
48     return *this = MyComplex((a*c.a+b*c.b)/(c.b*c.b+c.a*c.a),(b*c.a-a*c.b)/(c.b*c.b+c.a*c.a));
49 }
50 
51 
52 ostream& operator <<(ostream &stream, MyComplex& mc){    
53     stream<< "(" << mc.a;
54     stream.setf(std::ios::showpos);
55     stream<< mc.b << "i)";
56     stream.unsetf(std::ios::showpos);
57     return stream;
58 }
59 istream& operator>>(istream &stream, MyComplex& mc){
60     stream>>mc.a>>mc.b;
61     return stream;
62 }
63 
64 int main() {
65     MyComplex z1, z2;
66     cin >> z1;
67     cin >> z2;
68     
69     cout<<z1.a<<" "<<z1.b<<endl;
70     cout<<z2.a<<" "<<z2.b<<endl;
71     
72     cout << "z1 + z2 = "      << z1 + z2      << endl;
73     cout << "z1 - z2 + z1 = " << z1 - z2 + z1 << endl;
74     cout << "z1 * z2 - z1 = " << z1 * z2 - z1 << endl;
75     cout << "z1 / z2 + z1 = " << z1 / z2 + z1 << endl;
76     cout << "z2 - z1 / z1 = " << z2 - z1 / z1;
77     // GCC及VC编译器在调试模式下会暂停,便于查看运行结果
78 #if ( defined(__DEBUG__) || defined(_DEBUG) )
79     cin.ignore(numeric_limits<streamsize>::max(), '\n');
80     cin.get();
81 #endif
82     return 0;
83 }