/* * cpx.c - implementation of a simple complex number package * version 2: struct pointer parameters & string dynamic allocation * CSE 413 demo 11/06 HP */ #include #include #include "cpx.h" /* number of characters in dynamic string result of cpx2str (including '\0' */ #define STRCHRS 100 /* return a complex number with real part = x and imaginary = y */ Complex mk_complex(double x, double y) { Complex result; result.re = x; result.im = y; return result; } /* return the sum of complex numbers c and d */ Complex cpx_add(Complex* c, Complex* d) { Complex result; /*result = mk_complex((*c).re + (*d).re, (*c).im + (*d).im); */ result = mk_complex(c->re + d->re, c->im + d->im); return result; } /* return a representation of c as re+im i in a newly allocated string */ char* cpx2str(Complex* c) { char* result; result = (char *)malloc(STRCHRS); sprintf(result, "%g+%gi", c->re, c->im); return result; }