欢迎来到天天文库
浏览记录
ID:38594150
大小:23.00 KB
页数:4页
时间:2019-06-15
《【例6.5】用重载运算符的方法进行复数运算》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、【例6.5】用重载运算符的方法进行复数运算#includeclasscomplex{floatreal,imag;//复数的实部和虚部public:complex(floatr=0,floati=0){real=r;imag=i;}voidprint();friendcomplexoperator+(complexa,complexb);friendcomplexoperator-(complexa,complexb);friendcomplexoperator*(complexa,complexb);frien
2、dcomplexoperator/(complexa,complexb);};voidcomplex::print(){cout<0)cout<<"+";//image小于0,则自带-if(imag!=0)cout<3、omplexb){complextemp;temp.real=a.real-b.real;temp.imag=a.imag-b.imag;returntemp;}complexoperator*(complexa,complexb){complextemp;temp.real=a.real*b.real-a.imag*b.imag;temp.imag=a.real*b.imag+a.imag*b.real;returntemp;}complexoperator/(complexa,complexb){complextemp;floatt4、t;tt=1/(b.real*b.real+b.imag*b.imag);temp.real=(a.real*b.real+a.imag*b.imag)*tt;temp.imag=(b.real*a.imag-a.real*b.imag)*tt;returntemp;}voidmain(){complexc1(2.3,4.6),c2(3.6,2.8),c3;c1.print();c2.print();c3=c1+c2;c3.print();c3=c1-c2;c3.print();c3=c1*c2;c3.print();c3=c1/c2;5、c3.print();}程序的运行结果为:2.3+4.6i3.6+2.8i5.9+7.4i-1.3+1.8i-4.6+23i1.01731+0.486538i
3、omplexb){complextemp;temp.real=a.real-b.real;temp.imag=a.imag-b.imag;returntemp;}complexoperator*(complexa,complexb){complextemp;temp.real=a.real*b.real-a.imag*b.imag;temp.imag=a.real*b.imag+a.imag*b.real;returntemp;}complexoperator/(complexa,complexb){complextemp;floatt
4、t;tt=1/(b.real*b.real+b.imag*b.imag);temp.real=(a.real*b.real+a.imag*b.imag)*tt;temp.imag=(b.real*a.imag-a.real*b.imag)*tt;returntemp;}voidmain(){complexc1(2.3,4.6),c2(3.6,2.8),c3;c1.print();c2.print();c3=c1+c2;c3.print();c3=c1-c2;c3.print();c3=c1*c2;c3.print();c3=c1/c2;
5、c3.print();}程序的运行结果为:2.3+4.6i3.6+2.8i5.9+7.4i-1.3+1.8i-4.6+23i1.01731+0.486538i
此文档下载收益归作者所有