C 库 - creal() 函数
C complex 库中的 creal() 函数通常用于提取复数的实部。复数由两部分组成:实部和虚部 (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
", 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;
// 使用 CMPLX 函数创建复数
double complex z = CMPLX(real, imag);
printf("The complex number is: %.2f + %.2fi
", creal(z), cimag(z));
// 获取实部
// 使用 creal()
printf("The real part of z: %.1f
", 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;
// 获取实部
double realNum = creal(z);
// 打印结果
printf("The Complex number: %.2f + %.2fi
", creal(z), cimag(z));
printf("The Real part: %.2f
", realNum);
return 0;
}
输出
以下是输出 -
The Complex number: 10.00 + 5.00i The Real part: 10.00

