8_72.cpp
上传用户:zipjojo
上传日期:2009-07-20
资源大小:70k
文件大小:2k
源码类别:

文章/文档

开发平台:

C/C++

  1. #include<iostream.h>
  2. class complex
  3. {
  4. float a,b;
  5. public:
  6. complex(){a=0.0;b=0.0;cout<<"默认构造函数执行!";}
  7. complex(float x,float y) {a=x;b=y;cout<<"构造函数执行!";}
  8. friend complex Add(complex& comp1,complex& comp2);
  9. friend complex Sub(complex& comp1,complex& comp2);
  10. friend complex Mul(complex& comp1,complex& comp2);
  11. friend void Div(complex& comp1,complex& comp2);
  12. friend void disp(complex& comp1)
  13. {
  14. if(comp1.b>0)
  15. cout<<comp1.a<<"+"<<comp1.b<<"i"<<endl;
  16. else
  17. cout<<comp1.a<<"-"<<-comp1.b<<"i"<<endl;
  18. }
  19. void disp()
  20. {
  21. if(b>0)
  22. cout<<a<<"+"<<b<<"i"<<endl;
  23. else
  24. cout<<a<<"-"<<-b<<"i"<<endl;
  25. }
  26. };
  27.  complex Add(complex& comp1,complex& comp2)
  28. {
  29. float x=comp1.a+comp2.a;
  30. float y=comp1.b+comp2.b;
  31. return complex(x,y);
  32. }
  33. complex Sub(complex& comp1,complex& comp2)
  34. {
  35. float x=comp1.a-comp2.a;
  36. float y=comp1.b-comp2.b;
  37. return complex(x,y);
  38. }
  39. complex Mul(complex& comp1,complex& comp2)
  40. {
  41. float x=comp1.a*comp2.a-comp1.b*comp2.b;
  42. float y=comp1.a*comp2.b+comp1.b*comp2.a;
  43. return complex(x,y);
  44. }
  45. void Div(complex& comp1,complex& comp2)
  46. {
  47. if((comp2.a*comp2.a+comp2.b*comp2.b)!=0)
  48. {
  49.     float x=(comp1.a*comp2.a+comp1.b*comp2.b)/(comp2.a*comp2.a+comp2.b*comp2.b);
  50.     float y=(comp1.b*comp2.a-comp1.a*comp2.b)/(comp2.a*comp2.a+comp2.b*comp2.b);
  51. cout<<"复数s1、s2之商为:";
  52.         if(y>0)
  53.   cout<<x<<"+"<<y<<"i"<<endl;
  54.     else
  55.   cout<<x<<"-"<<-y<<"i"<<endl;
  56. }
  57. else
  58. cout<<"除数为零,不能相除!";
  59. }
  60. void main()
  61. {
  62. complex s1(1,2),s2(3,4);
  63. cout<<"复数s1:";
  64. s1.disp();
  65. cout<<"复数s2:";
  66. s2.disp();
  67. cout<<"复数s1、s2之和为:";
  68. disp(Add(s1,s2));
  69. cout<<"复数s1、s2之差为:";
  70. disp(Sub(s1,s2));
  71. cout<<"复数s1、s2之积为:";
  72. disp(Mul(s1,s2));
  73. Div(s1,s2);
  74. cout<<endl;
  75. }