C complex number and printf

别来无恙 提交于 2019-11-27 08:33:16
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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!