Basic and Advance C Question:
Download Job Interview Questions and Answers PDF
What is a good way to implement complex numbers in C?
Answer:
It is straightforward to define a simple structure and some arithmetic functions to manipulate them. C99 supports complex as a standard type. Here is a tiny example, to give you a feel for it:
typedef struct {
double real;
double imag;
} complex;
#define Real(c) (c).real
#define Imag(c) (c).imag
complex cpx_make(double real, double imag)
{
complex ret;
ret.real = real;
ret.imag = imag;
return ret;
}
complex cpx_add(complex a, complex b)
{
return cpx_make(Real(a) + Real(b), Imag(a) + Imag(b));
}
You can use these routines with code like
complex a = cpx_make(1, 2);
complex b = cpx_make(3, 4);
complex c = cpx_add(a, b);
or, even more simply,
complex c = cpx_add(cpx_make(1, 2), cpx_make(3, 4));
typedef struct {
double real;
double imag;
} complex;
#define Real(c) (c).real
#define Imag(c) (c).imag
complex cpx_make(double real, double imag)
{
complex ret;
ret.real = real;
ret.imag = imag;
return ret;
}
complex cpx_add(complex a, complex b)
{
return cpx_make(Real(a) + Real(b), Imag(a) + Imag(b));
}
You can use these routines with code like
complex a = cpx_make(1, 2);
complex b = cpx_make(3, 4);
complex c = cpx_add(a, b);
or, even more simply,
complex c = cpx_add(cpx_make(1, 2), cpx_make(3, 4));
Download C Programming Interview Questions And Answers
PDF
Previous Question | Next Question |
I am having trouble with a Turbo C program which crashes | The predefined constant M_PI seems to be missing from my machines copy of math.h. |