Exercise 5-7 Use functions to approximate the cosine function (15 point(s))

This question requires the realization of a function, use the following formula to find the approximate value of cos(x), accurate to the absolute value of the last term is less than e:
cos(x)=x^​0 /0!−x 2/2!+x 4/ 4!−x^6/6!+...

Function interface definition:

double funcos( double e, double x );

The parameters passed in by the user are the upper limit of error e and the independent variable x; the function funcos should return the approximate value of cos(x) calculated with the given formula and meet the error requirements. Both input and output are in the double precision range.

Sample referee test procedure:

#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;
}

/* 你的代码将被嵌在这里 */

Input sample:

0.01 -3.14

Sample output:

cos(-3.14) = -0.999899

answer:

double funcos( double e, double x )
{
    
     //这边把第一项的值直接赋值给变量,循环时从第二项开始算的 
	double j=1.0; //分子的次方 (初值为1,因为第一项分子最后结果为1)
	int t=-1; //中间变量(实现一正一负) (由于第一项是正的,所以这里应当为负的,因为循环从第二项开始算) 
	double sum=1.0; //cos近似值 (初值为1,因为第一项的值最后结果为1)
	int s=1; //循环变量 
	double p=1; //分母阶乘 (初值为1,因为第一项分母的阶乘为1)
	double m=j/p; //每一项的值(不含符号) 
	do
	{
    
    
		p=p*s*(s+1);  //分母阶乘 (公式的由来:一步一步验算,跟初值s有很大的关系)
		j=j*x*x;  //分子x的次方 
		sum=sum+j/p*t; //总和 
		m=j/p; //每一项的值 
		t=-t; //每次循环快结束的时候t要变号 
		s+=2; //循环变量加2 
	}
	while(m>=e); //当每一项的值大于误差时循环 
	return sum; //返回sum给funcos 
}

Guess you like

Origin blog.csdn.net/qq_44715943/article/details/114584376