PTA 使用函式求餘弦函式的近似值
阿新 • • 發佈:2021-01-07
技術標籤:pta
習題5-7 使用函式求餘弦函式的近似值 (15分)
本題要求實現一個函式,用下列公式求cos(x)的近似值,精確到最後一項的絕對值小於e:
cos(x)=x0/0!−x2/2!+x4/4!−x6/6!+⋯
#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;
}
double jie(double a)
{double i,sum=1.0;
for(i=1;i<=a;i++)
{sum=sum*i;
}
return sum;
}
double funcos( double e, double x )
{ double cos=1.0;
double flag=-1;
double i=2.0;
while(i)
{cos=cos+(pow(-1,(i/2.0))*pow(x,i))/jie(i);
i+ =2.0;
printf("%lf ",cos);
if((pow(x,i)/jie(i))<e) break;
}
return cos;
}
精度較高時,不能用階乘,答案還錯了。。。。