首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言實現複數運算:C99 complex.h 標準庫完整指南

     編輯:關於C

C99 原生複數支援

自 C99 起,<complex.h> 提供標準複數類型與運算,無需手工實現結構體。三種精度:

  • float _Complex / float complex
  • double _Complex / double complex
  • long double _Complex / long double complex

宏 I 表示虛部單位(I*I == -1),complex 為 _Complex 別名。

核心 API

完整演示程序

#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>。
  • 嵌入式工具鏈:確認庫支援,否則回退自定義結構體實現。

避坑指南

  1. 不要混用精度:float complex 與 double complex 運算會隱式轉換,可能丟失精度或產生警告。
  2. 格式化輸出:printf 無直接複數格式符,需拆分 creal()/cimag() 打印。
  3. 虛部單位:用 I 宏,勿自定義 #define I 1.0fi 等,標準宏類型正確。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
功能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