fork download
  1. #include <stdio.h>
  2. #include <string>
  3.  
  4. class Complex {
  5. private:
  6. int a, b;
  7.  
  8. public:
  9. Complex(int real) {
  10. a = real;
  11. b = 0;
  12. }
  13.  
  14. Complex(int real, int imag) {
  15. a = real;
  16. b = imag;
  17. }
  18.  
  19. Complex(const Complex &c) {
  20. *this = c;
  21. }
  22.  
  23. Complex &operator=(const Complex &c) {
  24. a = c.a;
  25. b = c.b;
  26. return *this;
  27. }
  28.  
  29. Complex &operator+=(const Complex &c) {
  30. a += c.a;
  31. b += c.b;
  32. return *this;
  33. }
  34.  
  35. Complex &operator-=(const Complex &c) {
  36. a -= c.a;
  37. b -= c.b;
  38. return *this;
  39. }
  40.  
  41. Complex &operator*=(const Complex &c) {
  42. Complex tmp = *this;
  43. a = tmp.a * c.a - tmp.b * c.b;
  44. b = tmp.a * c.b + tmp.b * c.a;
  45. return *this;
  46. }
  47.  
  48. std::string str() const {
  49. char buf[32];
  50. if (b == 0) {
  51. snprintf(buf, sizeof(buf), "%d", a);
  52. } else if (a == 0) {
  53. if (b == -1) return "-i";
  54. if (b == 1) return "i";
  55. snprintf(buf, sizeof(buf), "%di", b);
  56. } else if (b == -1) {
  57. snprintf(buf, sizeof(buf), "%d-i", a);
  58. } else if (b < 0) {
  59. snprintf(buf, sizeof(buf), "%d%di", a, b);
  60. } else if (b == 1) {
  61. snprintf(buf, sizeof(buf), "%d+i", a);
  62. } else {
  63. snprintf(buf, sizeof(buf), "%d+%di", a, b);
  64. }
  65. return buf;
  66. }
  67. };
  68.  
  69. Complex operator+(const Complex &c1, const Complex &c2) {
  70. Complex ret = c1;
  71. ret += c2;
  72. return ret;
  73. }
  74.  
  75. Complex operator-(const Complex &c1, const Complex &c2) {
  76. Complex ret = c1;
  77. ret -= c2;
  78. return ret;
  79. }
  80.  
  81. Complex operator*(const Complex &c1, const Complex &c2) {
  82. Complex ret = c1;
  83. ret *= c2;
  84. return ret;
  85. }
  86.  
  87. int main() {
  88. Complex i(0, 1);
  89. Complex a = 1 + 2*i;
  90. Complex b = 3 + 4*i;
  91. Complex c = a + b;
  92. Complex d = a * b;
  93. Complex e = a - 1;
  94. Complex f = a - 2*i;
  95. printf("a = %s\n", a.str().c_str());
  96. printf("b = %s\n", b.str().c_str());
  97. printf("c = %s\n", c.str().c_str());
  98. printf("d = %s\n", d.str().c_str());
  99. printf("e = %s\n", e.str().c_str());
  100. printf("f = %s\n", f.str().c_str());
  101. }
  102.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
a = 1+2i
b = 3+4i
c = 4+6i
d = -5+10i
e = 2i
f = 1