题目描述
本题要求实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于eps。要求定义和调用函数funcos(eps,x)求余弦函数的近似值。
cos(x)=x0/0!−x2/2!+x4/4!−x6/6!+⋯
输入输出均在双精度范围内。
输入
两个实数eps(精度)和x
输出
见样例(分别保留2位与6位小数)
#include <stdio.h>
int fac(int x)
{
int a =1;
while(x)
{
a *= x;
x--;
}
return a;
}
double power(double x,int y)
{
double a =1;
while(y)
{
a *= x;
y--;
}
return a;
}
double count(double jindu ,double x )
{
double a = 0, sum = 0;
int i = 0 , flag = 1;
do {
a = 1.0 * power(x,i)/fac(i);
double b = a * flag;
flag = - flag;
sum =sum + b;
i += 2;
}while(a>jindu);
return sum;
}
int main()
{
double jindu, x, sum;
scanf("%lf %lf",&jindu,&x);
sum =count(jindu,x);
printf("cos(%.2lf) = %.6lf",x,sum);
return 0;
}