第七周C++实验报告(3)

来源:互联网 发布:知乎数据挖掘考研 编辑:程序博客网 时间:2024/05/29 07:22
  1. #include<iostream>     
  2. using namespace std;    
  3. template<class T>    
  4. class Complex       
  5. {    
  6. public:    
  7.     Complex( ){real=0;imag=0;}         
  8.     Complex(T r,T i){real=r;imag=i;}     
  9.     Complex complex_add(Complex &c2);     
  10.     Complex complex_subtract(Complex &c2);     
  11.     Complex complex_multiply(Complex &c2);     
  12.     Complex complex_divide(Complex &c2);     
  13.     void display( );       
  14. private:    
  15.     T real;     
  16.     T imag;     
  17. };  
  18.     
  19. template <class T>    
  20. Complex<T> Complex<T>::complex_add(Complex &c2)    
  21. {    
  22.     Complex c;    
  23.     c.real=real+c2.real;    
  24.     c.imag=imag+c2.imag;    
  25.     return c;    
  26. }  
  27.      
  28. template <class T>    
  29. Complex<T> Complex<T>::complex_subtract(Complex &c2)    
  30. {    
  31.     Complex c;    
  32.     c.real=real-c2.real;    
  33.     c.imag=imag-c2.imag;    
  34.     return c;    
  35. }  
  36.     
  37. template <class T>    
  38. Complex<T> Complex<T>::complex_multiply(Complex &c2)    
  39. {    
  40.     Complex c;    
  41.     c.real=real*c2.real-imag*c2.imag;    
  42.     c.imag=real*c2.imag+imag*c2.real;    
  43.     return c;    
  44. }  
  45.      
  46. template <class T>    
  47. Complex<T> Complex<T>::complex_divide(Complex &c2)    
  48. {    
  49.     Complex c,c3,c4;    
  50.     c3.real=c2.real;    
  51.     c3.imag=c2.imag;  
  52.     c.real=real*c3.real+imag*c3.imag;    
  53.     c.imag=(-real*c3.imag)+imag*c3.real;      
  54.     c4.real=c2.real*c2.real+c2.imag*c3.imag;    
  55.     c.real=c.real/c4.real;    
  56.     c.imag=c.imag/c4.real;    
  57.     return c;    
  58. }  
  59.       
  60. template <class T>      
  61. void Complex<T>::display( )       
  62. {    
  63.     cout<<"("<<real<<","<<imag<<"i)"<<endl;    
  64. }  
  65.     
  66. int main( )    
  67. {      
  68.     //实现加运算  
  69.     Complex<int> c1(3,4),c2(5,-10),c3;      
  70.     c3=c1.complex_add(c2);      
  71.     cout<<"c1+c2=";     
  72.     c3.display( );  
  73.     //实现减运算  
  74.     Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;      
  75.     c6=c4.complex_subtract(c5);      
  76.     cout<<"c4-c5=";     
  77.     c6.display( );     
  78.     //实现乘运算  
  79.     Complex<double> c7(3,4.5),c8(6.3,-1.89),c9;      
  80.     c9=c7.complex_multiply(c8);      
  81.     cout<<"c7*c8=";     
  82.     c9.display( );     
  83.     //实现除运算  
  84.     Complex<double> c10(3.7,3),c11(4,5.5),c12;      
  85.     c12=c10.complex_divide(c11);      
  86.     cout<<"c10/c11=";     
  87.     c12.display( );     
  88.     system("pause");    
  89.     return 0;