复数类Complex.cpp 659 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include <iostream>
  2. using namespace std;
  3. class Complex {
  4. private:
  5. double real;
  6. double imag;
  7. public:
  8. Complex(double r, double i = 0) : real(r), imag(i) {}
  9. void add(const Complex &other) {
  10. real += other.real;
  11. imag += other.imag;
  12. }
  13. void show() const {
  14. cout << real;
  15. if (imag >= 0)
  16. cout << "+" << imag << "i" << endl;
  17. else
  18. cout << "-" << -imag << "i" << endl;
  19. }
  20. };
  21. int main() {
  22. Complex c1(3, 5);
  23. Complex c2 = 4.5;
  24. cout << "c1=";
  25. c1.show();
  26. cout << "c2=";
  27. c2.show();
  28. c1.add(c2);
  29. cout << "c1+c2=";
  30. c1.show();
  31. return 0;
  32. }