C 库 - CMPLX() 函数
C complex 库中的 CMPLX() 函数通常用于生成由实部和虚部 (imag) 组成的复数。
如果实部和虚部为浮点型,我们可以使用 cmplxf() 生成复数,并使用 crealf() 和 cimagf() 获取实部和虚部;对于长双精度型,可以使用 cmplxl()、creall() 和 cimagl()。
此函数可用于科学和工程应用,包括信号处理、控制系统和量子力学。
语法
以下是 C 库CMPLX() 函数的语法 -
double complex CMPLX( double real, double imag );
参数
此函数接受以下参数 -
-
real - 表示复数的实部。它是 double 类型。
-
imag - 表示复数的虚部 (imag)。它是双精度型。
返回值
此函数返回一个双精度型复数。
示例 1
以下是一个简单的 C 程序,演示如何使用 CMPLX() 生成复数。
#include <stdio.h> #include <complex.h> int main() { double real = 3.0; double imag = 4.0; // 使用 CMPLX 函数创建复数 double complex z = CMPLX(real, imag); printf("The complex number is: %.2f + %.2fi", creal(z), cimag(z)); return 0; }
输出
以下是输出 -
The complex number is: 3.00 + 4.00i
示例 2
计算共轭
我们来看另一个示例,我们使用 CMPLX() 函数创建复数,然后使用 'conj()' 函数计算复数的共轭。
#include <stdio.h> #include <complex.h> int main() { double real = 3.0; double imag = 4.0; // 使用 CMPLX 函数创建复数 double complex z = CMPLX(real, imag); printf("The complex number is: %.2f + %.2fi", creal(z), cimag(z)); // 计算 conjugate double complex z_conjugate = conj(z); printf("The conjugate of the complex number is: %.2f + %.2fi", creal(z_conjugate), cimag(z_conjugate)); return 0; }
输出
以下是输出 -
The complex number is: 3.00 + 4.00i The conjugate of the complex number is: 3.00 + -4.00i
示例 3
对复数执行算术运算
以下示例生成两个复数并对它们执行算术运算。
#include <stdio.h> #include <complex.h> int main() { double real1 = 2.0, imag1 = 3.0; double real2 = 4.0, imag2 = -5.0; // 使用 CMPLX 函数 double complex z1 = CMPLX(real1, imag1); double complex z2 = CMPLX(real2, imag2); // 算术运算 double complex sum = z1 + z2; double complex diff = z1 - z2; // 显示运算结果 printf("Complex number z1: %.2f + %.2fi", creal(z1), cimag(z1)); printf("Complex number z2: %.2f + %.2fi", creal(z2), cimag(z2)); printf("Sum: %.2f + %.2fi", creal(sum), cimag(sum)); printf("Difference: %.2f + %.2fi", creal(difference), cimag(difference)); return 0; }
输出
以下是输出 -
Complex number z1: 2.00 + 3.00i Complex number z2: 4.00 + -5.00i Sum: 6.00 + -2.00i Difference: -2.00 + 8.00i