1 #include <iostream> 2 using namespace std; 3 typedef struct { 4 double real; //复数的实部 5 double imag; //复数的虚部 6 } Complex; 7 8 //复数的初始化 9 void initial(Complex *&z) 10 { 11 z=new Complex; //给形参z一个复数的空间 12 } 13 14 //复数的赋值 15 void assignment(Complex *&z,double v1,double v2) 16 { 17 z->real=v1; 18 z->imag=v2; 19 } 20 //复数的输出 21 void output(Complex *z) 22 { 23 if(z->real) 24 { 25 if(z->imag==0) 26 cout<<z->real<<endl; 27 else if(z->imag==-1) 28 cout<<z->real<<"-i"<<endl; 29 else if(z->imag==1) 30 cout<<z->real<<"+"<<"i"<<endl; 31 else if(z->imag>0) 32 cout<<z->real<<"+"<<z->imag<<"i"<<endl; 33 else 34 cout<<z->real<<z->imag<<"i"<<endl; 35 } 36 else 37 { 38 if(z->imag==0) 39 cout<<"0"<<endl; 40 else if(z->imag==-1) 41 cout<<"-i"<<endl; 42 else if(z->imag==1) 43 cout<<"i"<<endl; 44 else 45 cout<<z->imag<<"i"<<endl; 46 47 } 48 } 49 //复数的和 50 void sum(Complex *z1,Complex *z2,Complex *&sum) 51 { 52 sum->real=z1->real+z2->real; 53 sum->imag=z1->imag+z2->imag; 54 } 55 56 //复数的差 57 void difference(Complex *z1,Complex *z2,Complex *&dif) 58 { 59 dif->real=z1->real-z2->real; 60 dif->imag=z1->imag-z2->imag; 61 } 62 63 //复数的商 64 void Quotient(Complex *z1,Complex *z2,Complex *&quo) 65 { 66 if(z2->real*z2->real+z2->imag*z2->imag) 67 { 68 quo->real=(z1->real*z2->real+z1->imag*z1->imag)/(z2->real*z2->real+z2->imag*z2->imag); 69 quo->imag=(z2->real*z1->imag-z1->real*z2->imag)/(z2->real*z2->real+z2->imag*z2->imag); 70 } 71 else 72 { 73 cout<<"z1和z2无法进行相除,非法"; 74 } 75 76 } 77 78 //复数的销毁 79 void destroy(Complex *z) 80 { 81 delete z; 82 } 83 84 //复数的积 85 void product(Complex *z1,Complex *z2,Complex *&prod) 86 { 87 prod->real=z1->real*z2->real-z1->imag*z2->imag; 88 prod->imag=z1->real*z2->imag+z1->imag*z2->real; 89 } 90 int main() 91 { 92 double a,b; 93 cout<<"请输入第一个复数的实部:";cin>>a; 94 cout<<"请输入第一个复数的虚部:";cin>>b; 95 Complex *z1;initial(z1); 96 assignment(z1,a,b); 97 cout<<"第一个复数为:";output(z1); 98 99 double c,d; 100 cout<<"请输入第二个复数的实部:";cin>>c; 101 cout<<"请输入第二个复数的虚部:";cin>>d; 102 Complex *z2;initial(z2); 103 assignment(z2,c,d); 104 cout<<"第二个复数为:";output(z2); 105 106 Complex *z3;initial (z3); 107 sum(z1,z2,z3); 108 cout<<"两个复数的和为:";output(z3); 109 110 Complex *diff;initial (diff); 111 difference(z1,z2,diff); 112 cout<<"两个复数的差为:";output(diff); 113 114 Complex *quot;initial(quot); 115 Quotient(z1,z2,quot); 116 cout<<"两个复数的商为:";output(quot); 117 118 Complex *pro;initial(pro); 119 product(z1,z2,pro); 120 cout<<"两个复数的积为:";output(pro); 121 122 destroy(z1); 123 destroy(z2); 124 cout<<"销毁成功z1,z2"<<endl; 125 126 127 }