求s(x) = x - x3/(3*1!)+x5/(5*2!)-x7/(7*3!)+…,预定求和精度为10-5。
结果 s(2) = 0.882084
#include <iostream>
#include <math.h>
using namespace std;
double sum(double x)
{
double f = x;//必须定义为double
int f1 = 1;
double f2 = 1;//必须定义为double
int tag = 1;
int i = 0;
double sum = 0;
double m;
m = tag * f / (f1 * f2);
while(fabs(m) >= 1e-5)
{
sum += m;
tag = -tag;
i++;
f = f * x * x;
f1 += 2;
f2 *= i;//不然此处为int
m = tag * f / (f1 * f2);//不然此处也为int
}
return sum;
}
int main()
{
cout<<sum(2);
}