C 庫 - CMPLX() 函式



C 的complexCMPLX() 函式通常用於生成由其實部和虛部 (imag) 組成的複數。

如果實部和虛部為“float”型別,我們可以使用cmplxf()生成複數,並使用crealf()cimagf()獲取實部和虛部,對於長雙精度型,使用cmplxl()creall()cimagl()

此函式可用於科學和工程應用,包括訊號處理、控制系統和量子力學。

語法

以下是CMPLX() 函式的 C 庫語法:

double complex CMPLX( double real, double imag );

引數

此函式接受以下引數:

  • real - 表示複數的實部。它是雙精度型。

  • imag - 表示複數的虛部 (imag)。它是雙精度型。

返回值

此函式返回一個雙精度型的複數。

示例 1

以下是一個基本的 C 程式,演示瞭如何使用CMPLX() 生成複數。

#include <stdio.h>
#include <complex.h>

int main() {
   double real = 3.0;
   double imag = 4.0;

   // Use the CMPLX function to create complex number
   double complex z = CMPLX(real, imag);
   printf("The complex number is: %.2f + %.2fi\n", 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;

   // Use the CMPLX function to create complex number
   double complex z = CMPLX(real, imag);

   printf("The complex number is: %.2f + %.2fi\n", creal(z), cimag(z));

   // Calculate conjugate
   double complex z_conjugate = conj(z);

   printf("The conjugate of the complex number is: %.2f + %.2fi\n", 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;
   
   // Use the CMPLX function 
   double complex z1 = CMPLX(real1, imag1);
   double complex z2 = CMPLX(real2, imag2);
   
   // Arithmetic operations 
   double complex sum = z1 + z2;
   double complex difference = z1 - z2;
   
   // Display the results of the operations
   printf("Complex number z1: %.2f + %.2fi\n", creal(z1), cimag(z1));
   printf("Complex number z2: %.2f + %.2fi\n", creal(z2), cimag(z2));
   printf("Sum: %.2f + %.2fi\n", creal(sum), cimag(sum));
   printf("Difference: %.2f + %.2fi\n", 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
c_library_complex_h.htm
廣告

© . All rights reserved.