這題事實上和上一題求 x^1/1! - x^2/2! +..... 這題很像
只是這裡我用了和那題不同的技巧,
以往通常要算幾項是需要 n 去決定
這裡用到的一點小技巧是....
1. 算出第 n 項的答案為 tmp1
2. 第 n-1 項的答案為 tmp2, |tmp2-tmp1|,檢查該誤差值是否夠小
3. 如果差值夠小的話,停下來,tmp1 即為所求,如果不夠小,tmp2=tmp1,進入下個回圈
於是,這裡必須定義一個可接受的誤差值(文中的 EPS),
如果 |tmp2-tmp1| < EPS, 代表算出來的值是可以接受的,
這時便可跳出回圈...
如果這個方法不是您所需要的,可以參考上一篇文章
x^1/1! - x^2/2! +.....
以下為原始碼.
// ============================================
// filename : Cos_func.cpp
// author : edison.shih.
// date : 2010.10.25
// complier : vc2008
//
// all rights reverse
// ============================================
#include <stdio.h>
#include <math.h>
#define EPS 1E-6
// cos(x) = 1- x^2/2! + x^4/4! - ....... x^n/n!
int main()
{
double x;
double n;
double a, b; // 分子,分母
double tmp1, tmp2; // 此項與上項答案
double delta = 0.0 ; // 答案誤差
double i, j;
printf("input x:");
scanf("%lf", &x);
tmp1 = 1.0, tmp2=1.0; // n=0 時,cos(x)=1
for(i=1.0; ; i=i+1.0){
a = pow(x, 2*i); // a = x^2, x^4, ...
// 2n!
n = 1.0;
for(j=1.0; j<=2*i; j=j+1.0) n = n*j;
// b = (-1)^i * 2n!
b = pow(-1.0, i) * n;
tmp1 = tmp1 + a/b;
delta = fabs(tmp2 - tmp1);
if(delta<EPS) break; // 誤差小於可接受範圍
else tmp2 = tmp1;
}
printf("Cos(%lf)=%lf\n", x, tmp1);
return 0;
}