54

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 "???"

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
gameboy
  • 1,505
  • 3
  • 15
  • 16

4 Answers4

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

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

John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
  • I could be wrong here, but as creal() and cimag() both return doubles, shouldn't the format specifier be '%lf' instead of simply '%f'? – Jon Doe Jun 30 '15 at 17:06
  • 5
    Additional improvement - macro which reacts to sign of imaginary part: `#define printfc(c) printf("%f%c%fi",creal(c),(cimag(c)>=0.0f)? '+':'\0',cimag(c))` – Agnius Vasiliauskas Sep 21 '15 at 19:02
  • 2
    @JonDoe It doesn't matter. printf is not scanf, f and lf are both ok for double. See http://stackoverflow.com/questions/210590/why-does-scanf-need-lf-for-doubles-when-printf-is-okay-with-just-f – ntysdd May 09 '17 at 02:16
  • @AgniusVasiliauskas Are you aware that `%c` will also output `\0`? Better use `%s` with `? "+" : ""` – 12431234123412341234123 Jul 01 '21 at 18:39
20

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.

levif
  • 2,156
  • 16
  • 14
0

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.

  • 2
    I would argue that relying on undefined behavior when debugging is a bad idea. Undefined behavior can often cause other subtle bugs, exacerbating the problem. Plus it is all too common for throwaway debugging code to end up in production. – David Brown Nov 22 '12 at 20:25
  • 3
    This will only work if the platform's calling conventions specifies that complex numbers are passed in the same way as two real numbers, which is in no way guaranteed. – Stephen Canon Nov 23 '12 at 01:57
  • 2
    It is, however, for debugging only, quite a nice hack. Thank you for the idea. – Rhys Ulerich Feb 13 '14 at 17:23
  • Currently using a compiler with _Complex but nothing else. Using the back-to-back in mem in a safer way as such: `printf("%f%+fi\n", (double)D, *((double*)&D+1));` – dargaud Jan 21 '20 at 15:23
-3

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);
Lou
  • 1