In C, imaginary
is a macro that enables the programmer to write pure imaginary numbers.
The
imaginary
macro expands to the_Imaginary
macro.
To use the imaginary
macro, the program needs to include the header file <complex.h>
as shown below:
#include <complex.h>
You can define a variable x
for pure imaginary numbers through the imaginary
macro in three ways:
float imaginary x
double imaginary x
long double imaginary x
The following code demonstrates how to declare, define, and print an imaginary number.
After declaring an imaginary number x
, it is added to a real number to form a complex number. The program then uses the creal()
function to extract the real number, followed by the cimag()
function to extract the imaginary number in order to print the complex number.
#include <stdio.h>#include <complex.h>int main(){// imaginarydouble complex x = 4.0 * I;// realdouble real = 9.0;// complex numberdouble complex num = real + x;// print complex numberprintf("z = %.1f%+.1fi\n", creal(num), cimag(num));}
Note: According to the official documentation, “A compiler that defines
__STDC_IEC_559_COMPLEX__
is not required to support imaginary numbers.” We can use thecomplex
macro instead of theimaginary
macro in line 7 and that will get the job done.
Free Resources