We use _Complex
to declare a complex number in C.
It is an expansion of the complex
macro in <complex.h>
A complex number is written as the sum of one real number and one real number multiplied by the imaginary unit, I.
The following are the three _Complex
types:
float _Complex
double _Complex
long double _Complex
By including the
<complex.h>
header, we can replace the_Complex
keyword withcomplex
and have the same effect.
#include <complex.h>#include <stdio.h>int main(void){//declaring a complex number using complexdouble complex z1 = 1 + 2*I;//Arithmetic operationz1 = 2 * z1;//Printing correct to 1dpprintf("2 * (1.0+2.0i) = %.1f%+.1fi\n", creal(z1), cimag(z1));//declaring a complex number using _Complexdouble _Complex z2 = 3 + 4*I;//Arithmetic operationz2 = 1 / z2;//Printing correct to 1dpprintf("1 / (3.0+4.0i) = %.1f%+.1fi\n", creal(z2), cimag(z2));}
In the above example, we declare two complex numbers.
To define the imaginary part of the number, we multiply a real number with I.
Next, we perform a mathematical operation on the complex numbers.
Finally, the results are printed.
creal()
andcimag()
are defined in the<complex.h>
header. We use these to extract the real and imaginary parts of a complex number, respectively.
Free Resources