Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- // define a structure
- struct complexStruct
- {
- double real;
- double imag;
- } ;
- // make a typedef
- typedef struct complexStruct complex;
- // function to create a new complex number
- complex newComplex(double r, double i)
- { // get memory
- complex * z = calloc(1, sizeof(complex));
- z->real = r; // store parameters in memory
- z->imag = i;
- return *z; // return what is stored at z
- }
- // add two complex numbers
- complex add(complex x, complex y)
- { // similar to newComplex
- complex * z = calloc(1, sizeof(complex));
- z->real = x.real+y.real;
- z->imag = x.imag+y.imag;
- return *z;
- }
- // output a complex number
- void output(complex x)
- {
- if (x.imag<0)
- printf("%f %fi\n",x.real,x.imag);
- else
- printf("%f +%fi\n", x.real, x.imag);
- }
- int main()
- {
- complex num1 = newComplex(1,2); // num1 is 1+2i
- complex num2 = newComplex(3,4);
- complex num3 = add(num1, num2);
- output(num3); // 4 + 6i
- complex num4= newComplex(1,-4);
- complex num5= add(num1, num4);
- output(num5); // 2-2i
- }
Advertisement
Add Comment
Please, Sign In to add comment