C 复数和 printf

发布于 2024-09-30 19:41:24 字数 337 浏览 0 评论 0原文

如何打印(使用 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;
}

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦幻的味道 2024-10-07 19:41:24
printf("%f + i%f\n", creal(result), cimag(result));

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

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

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

说不完的你爱 2024-10-07 19:41:24

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

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

输出:

0.000000+1.000000i

注意 i 位于末尾。

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.

迷路的信 2024-10-07 19:41:24

因为复数在内存中作为两个实数连续存储,所以这样做

printf("%g + i%g\n", result);

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

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.

绅士风度i 2024-10-07 19:41:24

使用 GNU C,这是可行的:

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

或者,如果您想在虚数部分后打印后缀“i”:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文