| 功能 | double 版 | float 版 | long double 版 |
| 取實部 | creal(z) | crealf(z) | creall(z) |
| 取虛部 | cimag(z) | cimagf(z) | cimagl(z) |
| 共軛 | conj(z) | conjf(z) | conjl(z) |
| 模/幅角 | cabs(z), carg(z) | 同前綴 f | 同前綴 l |
| 複數初等函數 | csin, ccos, cexp, csqrt, clog, cpow 等 | 前綴 f | 前綴 l |
完整演示程序
#include <stdio.h>
#include <complex.h>
#define ARR_LEN(arr) (sizeof(arr)/sizeof(arr[0]))
void demo_op(char op, double complex x, double complex y) {
double complex r = 0;
switch (op) {
case '+': r = x + y; break;
case '-': r = x - y; break;
case '*': r = x * y; break;
case '/': r = x / y; break;
}
printf("%.2f %c %.2f = %.2f %+.2fi\n",
creal(x), op, creal(y), creal(r), cimag(r));
}
int main(void) {
double complex x = 10.0 + 15.0*I;
double complex y = 20.0 - 5.0*I;
printf("x = %.2f %+.2fi\n", creal(x), cimag(x));
printf("y = %.2f %+.2fi\n", creal(y), cimag(y));
char ops[] = {'+', '-', '*', '/'};
for (int i = 0; i < ARR_LEN(ops); i++)
demo_op(ops[i], x, y);
// 複數初等函數示例
double complex z = 1.0 + 1.0*I;
printf("csqrt(1+i) = %.4f %+.4fi\n", creal(csqrt(z)), cimag(csqrt(z)));
printf("cexp(i*pi) = %.4f %+.4fi\n", creal(cexp(I*acos(-1))), cimag(cexp(I*acos(-1)))); // 欧拉公式 -1+0i
return 0;
}
輸出示例
x = 10.00 +15.00i
y = 20.00 -5.00i
10.00 + 20.00 = 30.00 +10.00i
10.00 - 20.00 = -10.00 +20.00i
10.00 * 20.00 = 275.00 +250.00i
10.00 / 20.00 = 0.56 +0.68i
csqrt(1+i) = 1.0987 +0.4551i
cexp(i*pi) = -1.0000 +0.0000i
編譯鏈接注意事項
- GCC/Clang:
-std=c99 -lm(部分需鏈接數學庫)。
- MSVC:VS 2013+ 支援 C99 複數,需包含
<complex.h>。
- 嵌入式工具鏈:確認庫支援,否則回退自定義結構體實現。
避坑指南
- 不要混用精度:
float complex 與 double complex 運算會隱式轉換,可能丟失精度或產生警告。
- 格式化輸出:
printf 無直接複數格式符,需拆分 creal()/cimag() 打印。
- 虛部單位:用
I 宏,勿自定義 #define I 1.0fi 等,標準宏類型正確。
- 上一篇文章: 三分查找算法:原理、C語言實現與凸性函數應用場景
- 下一篇文章: C語言實現自動化對拍工具:為競賽程式設計提升測試效率
Copyright ©
程式碼之家 All Rights Reserved