C complex number and printf

CPrintfComplex Numbers

C Problem Overview


How to print ( with printf ) complex number? For example, if I have this code:

#include <stdio.h>
#include <complex.h>
int main(void)
{
    double complex dc1 = 3 + 2*I;
    double complex dc2 = 4 + 5*I;
    double complex result;

    result = dc1 + dc2;
    printf(" ??? \n", result);
    
    return 0;
}

..what conversion specifiers ( or something else ) should I use instead "???"

C Solutions


Solution 1 - C

printf("%f + i%f\n", creal(result), cimag(result));

I don't believe there's a specific format specifier for the C99 complex type.

Solution 2 - C

Let %+f choose the correct sign for you for imaginary part:

printf("%f%+fi\n", crealf(I), cimagf(I));

Output:

0.000000+1.000000i

Note that i is at the end.

Solution 3 - C

Because the complex number is stored as two real numbers back-to-back in memory, doing

printf("%g + i%g\n", result);

will work as well, but generates compiler warnings with gcc because the type and number of parameters doesn't match the format. I do this in a pinch when debugging but don't do it in production code.

Solution 4 - C

Using GNU C, this works:

printf("%f %f\n", complexnum);

Or, if you want a suffix of "i" printed after the imaginary part:

printf("%f %fi\n", complexnum);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongameboyView Question on Stackoverflow
Solution 1 - CJohn CalsbeekView Answer on Stackoverflow
Solution 2 - ClevifView Answer on Stackoverflow
Solution 3 - CKipp CannonView Answer on Stackoverflow
Solution 4 - CLouView Answer on Stackoverflow