不使用 math.h 內建函數,自行實作 sin()、cos() 並計算:
sin(π/2)、sin(56°)、cos(87°)、cos(π/3)
sin(x) = x - x³/3! + x⁵/5! - x⁷/7! + ...cos(x) = 1 - x²/2! + x⁴/4! - x⁶/6! + ...rad = deg × π / 180#include <stdio.h>
#include <math.h> // 僅用於 M_PI 常數
#define PI 3.14159265358979323846
int factorial(int n);
double my_sin(double x);
double my_cos(double x);
int main() {
printf("sin(π/2) = %.10f\n", my_sin(PI/2));
printf("sin(56°) = %.10f\n", my_sin(56 * PI / 180));
printf("cos(87°) = %.10f\n", my_cos(87 * PI / 180));
printf("cos(π/3) = %.10f\n", my_cos(PI/3));
return 0;
}
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
double my_sin(double x) {
double sum = 0, term = x;
int n = 1, sign = 1;
while (fabs(term) > 1e-6) {
sum += sign * term;
n += 2;
term = pow(x, n) / factorial(n);
sign = -sign;
}
return sum;
}
double my_cos(double x) {
double sum = 0, term = 1;
int n = 0, sign = 1;
while (fabs(term) > 1e-6) {
sum += sign * term;
n += 2;
term = pow(x, n) / factorial(n);
sign = -sign;
}
return sum;
}

| 函數 | 手寫結果 | 標準庫值 | 絕對誤差 |
|---|---|---|---|
| sin(π/2) | 1.000000 | 1.000000 | ~1e-7 |
| sin(56°) | 0.829038 | 0.829038 | ~1e-7 |
| cos(87°) | 0.052336 | 0.052336 | ~1e-7 |
| cos(π/3) | 0.500000 | 0.500000 | ~1e-7 |
termₙ = -termₙ₋₂ × x² / (n×(n-1)),避免重複 pow 與階乘x 映射到 [-π/4, π/4] 區間加速收斂本題展示數值分析基礎,也是嵌入式、遊戲引擎、科學計算的核心技能。