简体   繁体   English

C复数和printf

[英]C complex number and printf

How to print ( with printf ) complex number? 如何打印(带printf)复数? 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 "???" ..我应该使用什么转换说明符(或其他东西)“???”

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

我不相信C99复杂类型有特定的格式说明符。

Let %+f choose the correct sign for you for imaginary part: %+f为你想象的部分选择正确的符号:

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

Output: 输出:

0.000000+1.000000i

Note that i is at the end. 请注意, i在最后。

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. 也会工作,但是使用gcc生成编译器警告,因为参数的类型和数量与格式不匹配。 I do this in a pinch when debugging but don't do it in production code. 我在调试时这样做,但不要在生产代码中执行此操作。

Using GNU C, this works: 使用GNU C,这适用:

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

Or, if you want a suffix of "i" printed after the imaginary part: 或者,如果您想在虚部之后打印后缀“i”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM