C语言 C 复数和 printf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4099433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:54:59  来源:igfitidea点击:

C complex number and printf

cprintfcomplex-numbers

提问by gameboy

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

如何打印(使用 printf )复数?例如,如果我有这个代码:

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

..我应该使用什么转换说明符(或其他)来代替“???”

回答by John Calsbeek

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

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

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

回答by levif

Let %+fchoose the correct sign for you for imaginary part:

让我们%+f为您的虚部选择正确的符号:

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

Output:

输出:

0.000000+1.000000i

Note that iis at the end.

注意i是在最后。

回答by Kipp Cannon

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.

也可以工作,但会使用 gcc 生成编译器警告,因为参数的类型和数量与格式不匹配。调试时我会在紧要关头这样做,但不要在生产代码中这样做。

回答by Lou

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