What is imaginary in C?

Share

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>

Syntax

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

Examples

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()
{
// imaginary
double complex x = 4.0 * I;
// real
double real = 9.0;
// complex number
double complex num = real + x;
// print complex number
printf("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 the complex macro instead of the imaginary macro in line 7 and that will get the job done.

Copyright ©2024 Educative, Inc. All rights reserved