当前位置:网站首页>01 use function to approximate cosine function (15 points)

01 use function to approximate cosine function (15 points)

2022-07-07 10:21:00 qq_ forty-two million one hundred and twenty thousand eight hun

Zhejiang University Edition 《C Language programming experiment and exercise guidance ( The first 3 edition )》 Topic collection

 Insert picture description here

Function interface definition

double funcos( double e, double x );

The parameter passed in by the user is the upper error limit e And independent variables x; function funcos Should return calculated with the given formula 、 And meet the error requirements cos(x) Approximate value . The input and output are within the double precision range

Example of Referee 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;
}

/* Your code will be embedded here */

sample input :

0.01 -3.14

sample output :

cos(-3.14) = -0.999899

My code

double fact(int n)
{
    

    if(n == 0)
    {
    
        return 1;
    }
    else
    return n*fact(n-1);
}

double funcos(double e,double x)
{
    
    double m = 0;
    int n = 0;  // Power and order multipliers 
    double res = 0;
    int flag = 1;   // Control sign 

    m = pow(x,n)/fact(n); 
    while(m >= e)
    {
    
         res += flag * m;
         n += 2;
         flag = -flag; // Change sign 
         m = pow(x,n)/fact(n); // Here is the absolute value of each term 
    }

    // The last one is that the accuracy is less than e Of 
    res += m;
    return res;
}

Submit results

 Insert picture description here

The reason for the error

The accuracy of the last term is less than e When the terms of are added to the sum Without symbol

Without symbol

Modified code

double fact(int n)
{
    

    if(n == 0)
    {
    
        return 1;
    }
    else
    return n*fact(n-1);
}

double funcos(double e,double x)
{
    
    double m = 0, res = 0;
    int n = 0;  // Power and order multipliers 
    int flag = 1;   // Control sign 

    m = pow(x,n)/fact(n);
    while(m >= e)
    {
    
         res += flag * m;
         n += 2;
         flag = -flag; // Change sign 
         m = pow(x,n)/fact(n); // Here is the absolute value of each term 
    }

    // The last one is that the accuracy is less than e Of 
    res += flag*m; // There's a leak here *flag Cause the second checkpoint error 
    return res;

}

Submit results

 Insert picture description here

原网站

版权声明
本文为[qq_ forty-two million one hundred and twenty thousand eight hun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130623100941.html