waltermilner

Untitled

Apr 28th, 2016
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4.  
  5. // define a structure
  6. struct complexStruct
  7. {
  8.     double real;
  9.     double imag;
  10. } ;
  11.  
  12. // make a typedef
  13. typedef struct complexStruct complex;
  14.  
  15. // function to create a new complex number
  16. complex newComplex(double r, double i)
  17. {   // get memory
  18.     complex * z = calloc(1, sizeof(complex));
  19.     z->real = r; // store parameters in memory
  20.     z->imag = i;
  21.     return *z; // return what is stored at z
  22. }
  23.  
  24. // add two complex numbers
  25. complex add(complex x, complex y)
  26. { // similar to newComplex
  27.     complex * z = calloc(1, sizeof(complex));
  28.     z->real = x.real+y.real;
  29.     z->imag = x.imag+y.imag;
  30.     return *z;
  31. }
  32.  
  33. // output a complex number
  34. void output(complex x)
  35. {
  36.     if (x.imag<0)
  37.         printf("%f %fi\n",x.real,x.imag);
  38.     else
  39.         printf("%f +%fi\n", x.real, x.imag);
  40.  
  41. }
  42.  
  43. int main()
  44. {
  45.     complex num1 = newComplex(1,2); // num1 is 1+2i
  46.     complex num2 = newComplex(3,4);
  47.  
  48.     complex num3 = add(num1, num2);
  49.     output(num3); // 4 + 6i
  50.     complex num4= newComplex(1,-4);
  51.     complex num5= add(num1, num4);
  52.     output(num5); // 2-2i
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment