#include
#include
double fact(int n)
{
double s = 1;
for(int i = 1; i <= n; i++)
{
s *= i;
}
return s;
}
double funcos(double e,int x)
{
//运算次序要理清
double cos = 0;
double item = 1;
int i = 0;
int flag = 1;
while(abs(item) >= e)
{
item = flag * pow(double (x), 2 * i) / fact(2 * i);
cos += item;
flag *= -1;
i++;
}
return cos;
}
int main()
{
int x = 0;
double e = 0;
printf("e: ");
scanf("%lf",&e);
printf("x: ");
scanf("%d",&x);
printf("cos(x) = %.3lf\n",funcos(e, x)); //唯一的缺陷就是3必须随e的变化手动改写
return 0;
}
运行结果: