本题要求实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于e:
cos(x)=x0/0!−x2/2!+x4/4!−x6/6!+⋯
函数接口定义:
double funcos( double e, double x );
其中用户传入的参数为误差上限e
和自变量x
;函数funcos
应返回用给定公式计算出来、并且满足误差要求的cos(x)的近似值。输入输出均在双精度范围内。
裁判测试程序样例:
#include <stdio.h>
#include <math.h>
double funcos( double e, double x );
int main()
{
double e, x;
scanf("%lf %lf", &e, &x);
printf("cos(%.2f) = %.6f\n", x, funcos(e, x));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
0.01 -3.14
结尾无空行
输出样例:
cos(-3.14) = -0.999899
结尾无空行
错误代码
double funcos( double e, double x )
{
int fuhao=-1,i,j;
double sum=1,chengjie=1;
for (i=2;;i+=2)
{
for (j=i-1;j<=i;j++)
{
chengjie*=j;
}
sum+=fuhao*pow(x,i)/chengjie ;
fuhao=-fuhao;
if (fabs(sum)<=e) return sum;
}
}
fabs内的不能填sum,会无法输出
解决方法:将sum改成pow(x,i)/chengjie