fork download
  1. #include <iostream>
  2. using namespace std;
  3. //____qcodep____
  4. class Complex
  5. {
  6. public:
  7. Complex(double r=0,double i=0)
  8. {
  9. re=r;im=i;
  10. }
  11. void add(Complex &p)
  12. {
  13. this->re+=p.re;
  14. this->im+=p.im;
  15. }
  16. void sub(Complex &p)
  17. {
  18. this->re-=p.re;
  19. this->im-=p.im;
  20. }
  21. void show()
  22. {
  23. if(re==0&&im==0) {cout<<0<<endl;return;}
  24. if(re!=0) cout<<re;
  25. if(re!=0&&im>0) cout<<"+"<<im<<"i"<<endl;
  26. else if(re==0&&im>0) cout<<im<<"i"<<endl;
  27. else if(im==0) cout<<endl;
  28. else cout<<im<<"i"<<endl;
  29. }
  30. private:
  31. double re,im;
  32. };
  33.  
  34.  
  35. int main()
  36. {
  37. double re, im;
  38. cin >> re >> im;
  39. Complex c1(re, im); // 用re, im初始化c1
  40. cin >> re;
  41. Complex c2 = re; // 用实数re初始化c2
  42.  
  43. c1.show();
  44. c2.show();
  45. c1.add(c2); // 将C1与c2相加,结果保存在c1中
  46. c1.show(); // 将c1输出
  47. c2.sub(c1); // c2-c1,结果保存在c2中
  48. c2.show(); // 输出c2
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5324KB
stdin
3 5
4.5
stdout
3+5i
4.5
7.5+5i
-3-5i