C 复数和 printf
如何打印(使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不认为 C99 复杂类型有特定的格式说明符。
I don't believe there's a specific format specifier for the C99 complex type.
让
%+f
为您的虚部选择正确的符号:输出:
注意
i
位于末尾。Let
%+f
choose the correct sign for you for imaginary part:Output:
Note that
i
is at the end.因为复数在内存中作为两个实数连续存储,所以这样做
也可以,但会因参数的类型和数量与格式不匹配而使用 gcc 生成编译器警告。我在调试时在紧要关头这样做,但不在生产代码中这样做。
Because the complex number is stored as two real numbers back-to-back in memory, doing
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.
使用 GNU C,这是可行的:
或者,如果您想在虚数部分后打印后缀“i”:
Using GNU C, this works:
Or, if you want a suffix of "i" printed after the imaginary part: