实验5-10 使用函数求余弦函数的近似值 (15 分)
浙大版《C语言程序设计实验与习题指导(第3版)》题目集
实验5-10 使用函数求余弦函数的近似值 (15 分)
本题要求实现一个函数,用下列公式求的近似值,精确到最后一项的绝对值小于:
函数接口定义:
double funcos( double e, double x );
其中用户传入的参数为误差上限和自变量;函数 funcos 应返回用给定公式计算出来、并且满足误差要求的的近似值。输入输出均在双精度范围内。
裁判测试程序样例:
#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
我的代码:
int factorial(int x){
int y = 1;
for(int i = x; i > 0; i--){
y *= i;
}
return y;
}
double funcos( double e, double x ){
double cos = 0, item = 1;
int i = 0, p = 1 ;
while(item >= e){
item = pow(x,i)/factorial(i);
cos += p * item;
i += 2;
p = -p;
}
return cos;
}
提交结果:
修改函数factorial的返回值为double之后正确
修改后的代码
double factorial(int x){
double y = 1;
for(int i = x; i > 0; i--){
y *= i;
}
return y;
}
double funcos( double e, double x ){
double cos = 0, item = 1;
int i = 0, p = 1 ;
while(item >= e){
item = pow(x,i)/factorial(i);
cos += p * item;
i += 2;
p = -p;
}
return cos;
}