PTA|《C语言程序设计(第3版)》习题5-7 使用函数求余弦函数的近似值 (15分)

题目

本题要求实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于e: c o s ( x ) = x 0 / 0 ! x 2 / 2 ! + x 4 / 4 ! x 6 / 6 ! + cos(x)=x^0/0!-x^2/2!+x^4/4!-x^6/6!+⋯

函数接口定义:

double funcos( double e, double x );

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

裁判测试程序样例:

#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

参考解答

double funcos( double e, double x ){
	if(x<0)x=-x;
    int flag=-1,i=2,j;
    double an=1,ret=1,fac=2,pow=x*x;
    while(an>=e){
        an=pow/fac;
        ret+=an*flag;
        flag=-flag;
        fac=fac*(i+1)*(i+2);
        pow=pow*x*x;
        i+=2;
    }
    return ret;
}
发布了86 篇原创文章 · 获赞 5 · 访问量 2090

猜你喜欢

转载自blog.csdn.net/weixin_44421292/article/details/104226608