习题5-7 使用函数求余弦函数的近似值 (15 分)
1. 题目摘自
https://pintia.cn/problem-sets/12/problems/307
2. 题目内容
本题要求实现一个函数,用下列公式求 cos(x)
的近似值,精确到最后一项的绝对值小于 e
:
18.png
函数接口定义:
double funcos( double e, double x );
其中用户传入的参数为误差上限 e
和自变量 x
;函数 funcos
应返回用给定公式计算出来、并且满足误差要求的 cos(x)
的近似值。输入输出均在双精度范围内。
输入样例:
0.01 -3.14
输出样例:
cos(-3.14) = -0.999899
3. 源码参考
#include<iostream>
#include<math.h>
using namespace std;
double funcos(double e, double x);
int fact(int n);
int main()
{
double e, x;
cin >> e >> x;
cout << "cos(" << x << ") = " << funcos(e, x) << endl;
return 0;
}
double funcos(double e, double x)
{
double s = 0, m;
int f = 1;
for (int i = 0; ; i++)
{
m = pow(x, i * 2) / fact(i * 2);
s += f * m;
f = -f;
if (m <= e)
{
break;
}
}
return s;
}
int fact(int n)
{
int s = 1;
for (int i = 1; i <= n; i++)
{
s *= i;
}
return s;
}