实验5-10 使用函数求余弦函数的近似值

  • 题目要求

  1. 实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于e:
  2. 函数接口定义:
double funcos( double e, double x );

其中用户传入的参数为误差上限e和自变量x;函数funcos应返回用给定公式计算出来、并且满足误差要求的cos(x)的近似值。输入输出均在双精度范围内。

  • 样例程序

  1. 裁判测试程序样例:
#include 
#include 
using namespace std;

double funcos(double e, double x);

int main()
{
    double e, x;
    cin >> e >> x;
    cout << "cos(" << x << ") = " << funcos(e, x) << endl;

    return 0;
}

/* 你的代码将被嵌在这里 */
  1. 输入样例
0.01 -3.14
  1. 输出样例
cos(-3.14) = -0.999899
  • 函数实现

double funcos(double e, double x)
{
    double numerator = 0, denominator = 1, term, value = 0;
    int i = 0;
    while(true)
    {  
        numerator = pow(x, i);
        term = pow(-1, i/2) * (numerator / denominator);
        value += term;
        denominator *= (i + 1)*(i + 2);
        i = i + 2;
        if (abs(term) < e)
            break;
    }   
    
    return value;
}

你可能感兴趣的:(实验5-10 使用函数求余弦函数的近似值)