C complex number and printf

后端 未结 4 1160
無奈伤痛
無奈伤痛 2020-12-01 11:38

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

#include 
#include 
int main(void)
{
    doubl         


        
相关标签:
4条回答
  • 2020-12-01 12:18

    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.

    0 讨论(0)
  • 2020-12-01 12:24

    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.

    0 讨论(0)
  • 2020-12-01 12:26
    printf("%f + i%f\n", creal(result), cimag(result));
    

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

    0 讨论(0)
  • 2020-12-01 12:36

    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);
    
    0 讨论(0)
提交回复
热议问题