求 x/1! - x^2/2! + x^3/3! - ... x^n/n!
一正一負的判斷方式非常多 ,
最笨的方法就是我下面用的方法,
pow....
math.h 裡面用到很多數值分析的技巧
如果簡單的就自己寫,速度或許些比較快
// ============================================
// filename : func1.cpp
// author : edison.shih.
// date : 2010.10.25
// complier : vc2008
//
// all rights reverse
// ============================================
#include <stdio.h>
#include <math.h>
// cos(x) = 1- x/1! - x^2/2! + x^3/3! - ... x^n/n!
int main()
{
double x;
double n;
double a, b, sum;
double i, j;
printf("input x and n:");
scanf("%lf %lf", &x, &n);
sum = 0.0;
for(i=1.0; i<=n; i++){
// n!
b = 1.0;
for(j=1.0; j<=i; j=j+1.0) b=b*j;
a = pow(x, i);
sum = sum + pow(-1.0, i)*a/b;
}
// sum = -x/1! + x^2/2! - x^3/3! + ... x^n/n!
// -sum = (x/1! - x^2/2! + x^3/3! - ... x^n/n!)
sum = -sum;
printf("x/1! - x^2/2! + x^3/3! - ... x^n/n! = %lf\n", sum);
return 0;
}