我如何处理C中的复数?我看到有一个complex.h
头文件,但它没有提供关于如何使用它的很多信息。
发布于 2018-04-18 08:23:51
这段代码可以帮助你:
#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;
}
发布于 2018-04-18 09:26:56
自C99标准(-std=c99
GCC的选项)以来,复杂类型是C语言。有些编译器甚至可以在更早期的模式下实现复杂类型,但这是非标准且不可移植的扩展(例如,IBM XL,GCC,可能是intel)。
你可以从http://en.wikipedia.org/wiki/Complex.h开始- 它给出了complex.h中函数的描述
本手册http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html还提供了有关宏的一些信息。
要声明一个复杂的变量,请使用 :
double _Complex a; // use c* functions without suffix
要么 :
float _Complex b; // use c*f functions - with f suffix
long double _Complex c; // use c*l functions - with l suffix
为了赋予复杂的值,可以使用以下_Complex_I
宏complex.h
:
float _Complex d = 2.0f + 2.0f*_Complex_I;
要直接访问(读/写)真实的图像部分,你可以使用这个不可移植的 GCC扩展:
__real__ a = 1.4;
__imag__ a = 2.0;
float b = __real__ a;
https://stackoverflow.com/questions/-100003908
复制相似问题