开发者

C complex number and printf

开发者 https://www.devze.com 2023-01-23 07:29 出处:网络
How to print ( with printf ) complex number? For example, if I have this code: #include <stdio.h>

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开发者_如何学Python;
    double complex result;

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

    return 0;
}

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


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

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


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.


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消