fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. class Complex {
  6. private:
  7. float real;
  8. float imaginary;
  9.  
  10. public:
  11. void set_values(float a, float b) {
  12. real = a;
  13. imaginary = b;
  14. }
  15.  
  16. // Single get() function using reference parameters
  17. void get(float* r, float* i) {// float &r likhleo hoito
  18. *r = real;
  19. *i = imaginary;
  20. }
  21.  
  22. void display() {
  23. if (imaginary < 0) {
  24. cout << real << "-" << abs(imaginary) << "i" << endl;
  25. } else {
  26. cout << real << "+" << imaginary << "i" << endl;
  27. }
  28. }
  29. };
  30.  
  31. class calculation {
  32. public:
  33. Complex sum(Complex a, Complex b) {
  34. Complex S;
  35. float x1, y1, x2, y2;
  36. a.get(&x1, &y1);
  37. b.get(&x2, &y2);
  38.  
  39. float x = x1 + x2;
  40. float y = y1 + y2;
  41. S.set_values(x, y);
  42. return S;
  43. }
  44.  
  45. Complex difference(Complex a, Complex b) {
  46. Complex D;
  47. float x1, y1, x2, y2;
  48. a.get(&x1, &y1);
  49. b.get(&x2, &y2);
  50.  
  51. float x = x1 - x2;
  52. float y = y1 - y2;
  53. D.set_values(x, y);
  54. return D;
  55. }
  56. };
  57.  
  58. int main() {
  59. float a, b;
  60.  
  61. cout << "Enter real and imaginary parts of first complex number: ";
  62. cin >> a >> b;
  63. Complex A, B, sum, diff;
  64. A.set_values(a, b);
  65.  
  66. cout << "Enter real and imaginary parts of second complex number: ";
  67. cin >> a >> b;
  68. B.set_values(a, b);
  69.  
  70. calculation calc;
  71. sum = calc.sum(A, B);
  72. diff = calc.difference(A, B);
  73.  
  74. cout << "\nSum = ";
  75. sum.display();
  76. cout << "Difference = ";
  77. diff.display();
  78.  
  79. return 0;
  80. }
  81.  
Success #stdin #stdout 0.01s 5172KB
stdin
Standard input is empty
stdout
Enter real and imaginary parts of first complex number: Enter real and imaginary parts of second complex number: 
Sum = -3.77869e-08+1.48706e-41i
Difference = 0+0i