如何在C中使用复数?我看到有一个complex.h头文件,但是它没有给我太多有关如何使用它的信息。如何有效地访问实部和虚部?是否有获取模块和阶段的本机函数?

最佳答案

这段代码将对您有所帮助,这是不言自明的:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

与:

creal(z1):获得实部(对于float crealf(z1),对于长双creall(z1))

cimag(z1):获得虚部(对于float cimagf(z1),对于长双cimagl(z1))

使用复数时要记住的另一个要点是,像cos()exp()sqrt()之类的函数必须用其复数形式替换,例如ccos()cexp()csqrt()

08-16 02:44