Is this flowchart right?

前端 未结 2 473
无人共我
无人共我 2020-12-07 06:03

I\'ve developed a C program that can calculate the value of a sin function using Taylor series expansion. I\'ve also drawn a flowchart for the program. The source code is g

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 06:31

    The risk with using a factorial function is that it very quickly goes out of int range. There is no need to have either a power function or a factorial function, because each term of the Taylor series can be derived from the previous term, by using a multiplication and a division.

    The multiplier is self-evident, simply the square of the angle.

    The divisor is i * (i - 1), the next two terms of the factorial.

    You will see I have removed your sign change factor t, because to change the sign of the previous term from neg to pos, or pos to neg, you just multiply by -1. But I have even removed that by reversing the sign of (i - 1) with my use of (1 - i).

    The first term of the series is simply rad so I start with that.

    #include 
    #include 
    
    int main()
    {
        int n, i;                                       // don't use `l` for a variable name 
        float deg, rad, radsq, val, term;
    
        printf("Enter degree of sin: ");
        if(scanf("%f", °) != 1) {
            return 1;                                   // or other error handling
        }
    
        printf("Enter limit of Taylor series: ");  
        if(scanf("%d", &n) != 1) {                           
            return 1;                                   // or other error handling
        }
        rad = deg * 3.14159265f / 180;                  // proper value for pi
        radsq = rad * rad;
    
        term = rad;                                     // first term is rad
        val = term;                                     // so is series sum
        for(i = 3; i <= n; i += 2)                      // we've done the first term
        {
            term *= radsq / (i * (1 - i));              // see explanation
            val += term;                                // sum the series
        }
    
        printf("\nValue calculated by program, using Taylor Series:\n");
        printf("Sin(%f) = %f\n", deg, val);
        printf("\nValue calculated using library function:\n");
        printf("Sin(%f) = %f\n", deg, sin(rad));
    
        return 0;
    }
    

提交回复
热议问题