fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct { float r, i; } C;
  4.  
  5. /* (a) Read complex number */
  6. C readC() {
  7. C c;
  8. printf("Enter real and imaginary parts: ");
  9. scanf("%f %f", &c.r, &c.i);
  10. return c;
  11. }
  12.  
  13. /* (b) Print complex number */
  14. void writeC(C c) {
  15. printf("%.1f + %.1fi\n", c.r, c.i);
  16. }
  17.  
  18. /* (c) Add & subtract */
  19. C add(C a, C b) { C t = { a.r + b.r, a.i + b.i }; return t; }
  20. C sub(C a, C b) { C t = { a.r - b.r, a.i - b.i }; return t; }
  21.  
  22. int main() {
  23. C c1 = readC();
  24. C c2 = readC();
  25.  
  26. printf("Addition: ");
  27. writeC(add(c1, c2));
  28.  
  29. printf("Subtraction: ");
  30. writeC(sub(c1, c2));
  31.  
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0s 5292KB
stdin
3 4 
2 5
stdout
Enter real and imaginary parts: Enter real and imaginary parts: Addition: 5.0 + 9.0i
Subtraction: 1.0 + -1.0i