C 庫 - creal() 函式



C 的complexcreal() 函式通常用於提取複數的實部。複數由兩個部分組成:實部和虛部 (imag)。

如果實部是“float”型別,我們可以使用crealf()獲取實部,對於長雙精度型,使用creall()

語法

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

double creal( double complex z );

引數

此函式接受單個引數:

  • Z - 它代表一個複數。

返回值

此函式返回複數 (z) 的實部。

示例 1

以下是一個基本的 C 程式,演示瞭如何使用 creal() 獲取複數 (z) 的實部。

#include <stdio.h>
#include <complex.h>
int main(void){
   double complex z = 1.0 + 2.0 * I;
   printf("The real part of z: %.1f\n", creal(z));
}

輸出

以下是輸出:

The real part of z: 1.0

示例 2

讓我們來看另一個例子,我們使用 creal() 函式來獲取生成的複數的實部。

#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));

   // obtain the real part
   // use creal()
   printf("The real part of z: %.1f\n", creal(z));

   return 0;
}

輸出

以下是輸出:

The complex number is: 3.00 + 4.00i
The real part of z: 3.0

示例 3

以下 creal() 函式的示例將演示如何將其與複數一起使用。

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

int main(void) {
   double complex z = 10.0 + 5.0 * I;
   // Get the real part 
   double realNum = creal(z);
   // Print the result
   printf("The Complex number: %.2f + %.2fi\n", creal(z), cimag(z));
   printf("The Real part: %.2f\n", realNum);
   return 0;
}

輸出

以下是輸出:

The Complex number: 10.00 + 5.00i
The Real part: 10.00
c_library_complex_h.htm
廣告
© . All rights reserved.