8_72.cpp
上传用户:zipjojo
上传日期:2009-07-20
资源大小:70k
文件大小:2k
- #include<iostream.h>
- class complex
- {
- float a,b;
- public:
- complex(){a=0.0;b=0.0;cout<<"默认构造函数执行!";}
- complex(float x,float y) {a=x;b=y;cout<<"构造函数执行!";}
- friend complex Add(complex& comp1,complex& comp2);
- friend complex Sub(complex& comp1,complex& comp2);
- friend complex Mul(complex& comp1,complex& comp2);
- friend void Div(complex& comp1,complex& comp2);
- friend void disp(complex& comp1)
- {
- if(comp1.b>0)
- cout<<comp1.a<<"+"<<comp1.b<<"i"<<endl;
- else
- cout<<comp1.a<<"-"<<-comp1.b<<"i"<<endl;
- }
- void disp()
- {
- if(b>0)
- cout<<a<<"+"<<b<<"i"<<endl;
- else
- cout<<a<<"-"<<-b<<"i"<<endl;
- }
- };
- complex Add(complex& comp1,complex& comp2)
- {
- float x=comp1.a+comp2.a;
- float y=comp1.b+comp2.b;
- return complex(x,y);
- }
- complex Sub(complex& comp1,complex& comp2)
- {
- float x=comp1.a-comp2.a;
- float y=comp1.b-comp2.b;
- return complex(x,y);
- }
- complex Mul(complex& comp1,complex& comp2)
- {
- float x=comp1.a*comp2.a-comp1.b*comp2.b;
- float y=comp1.a*comp2.b+comp1.b*comp2.a;
- return complex(x,y);
- }
- void Div(complex& comp1,complex& comp2)
- {
- if((comp2.a*comp2.a+comp2.b*comp2.b)!=0)
- {
- float x=(comp1.a*comp2.a+comp1.b*comp2.b)/(comp2.a*comp2.a+comp2.b*comp2.b);
- float y=(comp1.b*comp2.a-comp1.a*comp2.b)/(comp2.a*comp2.a+comp2.b*comp2.b);
- cout<<"复数s1、s2之商为:";
- if(y>0)
- cout<<x<<"+"<<y<<"i"<<endl;
- else
- cout<<x<<"-"<<-y<<"i"<<endl;
- }
- else
- cout<<"除数为零,不能相除!";
- }
- void main()
- {
- complex s1(1,2),s2(3,4);
- cout<<"复数s1:";
- s1.disp();
- cout<<"复数s2:";
- s2.disp();
- cout<<"复数s1、s2之和为:";
- disp(Add(s1,s2));
- cout<<"复数s1、s2之差为:";
- disp(Sub(s1,s2));
- cout<<"复数s1、s2之积为:";
- disp(Mul(s1,s2));
- Div(s1,s2);
- cout<<endl;
- }