C complex number and printf

2019-01-18 01:09发布

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

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-18 01:41

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.

查看更多
混吃等死
3楼-- · 2019-01-18 01:47
printf("%f + i%f\n", creal(result), cimag(result));

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

查看更多
不美不萌又怎样
4楼-- · 2019-01-18 01:49

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.

查看更多
登录 后发表回答