fork download
  1. // Complex numbers are entered by the user
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. typedef struct complex {
  7. float real;
  8. float imag;
  9. } complexNumber;
  10.  
  11. complexNumber addComplexNumbers(complex, complex);
  12.  
  13. int main() {
  14. complexNumber num1, num2, complexSum;
  15. char signOfImag;
  16.  
  17. cout << "For 1st complex number," << endl;
  18. cout << "Enter real and imaginary parts respectively:" << endl;
  19. cin >> num1.real >> num1.imag;
  20.  
  21. cout << endl
  22. << "For 2nd complex number," << endl;
  23. cout << "Enter real and imaginary parts respectively:" << endl;
  24. cin >> num2.real >> num2.imag;
  25.  
  26. // Call add function and store result in complexSum
  27. complexSum = addComplexNumbers(num1, num2);
  28.  
  29. // Use Ternary Operator to check the sign of the imaginary number
  30. signOfImag = (complexSum.imag > 0) ? '+' : '-';
  31.  
  32. // Use Ternary Operator to adjust the sign of the imaginary number
  33. complexSum.imag = (complexSum.imag > 0) ? complexSum.imag : -complexSum.imag;
  34.  
  35. cout << "Sum = " << complexSum.real << signOfImag << complexSum.imag << "i";
  36.  
  37. return 0;
  38. }
  39.  
  40. complexNumber addComplexNumbers(complex num1, complex num2) {
  41. complex temp;
  42. temp.real = num1.real + num2.real;
  43. temp.imag = num1.imag + num2.imag;
  44. return (temp);
  45. }
  46.  
Success #stdin #stdout 0.01s 5508KB
stdin
Standard input is empty
stdout
For 1st complex number,
Enter real and imaginary parts respectively:

For 2nd complex number,
Enter real and imaginary parts respectively:
Sum = 9.32172e+23+7.66805e-41i