Home > Blockchain >  can't implement Maclaurin's series
can't implement Maclaurin's series

Time:09-09

I wrote a program to calculate the value of cosx by Maclaurin's series and by library function.See the following

#include<stdio.h>
#include<math.h>
#define N 20
int main()
{
    float sum,y;
    int x,i=0;
    while(scanf("%d",&x)!=EOF)
    {   sum=0;
        for(i=0;i<=N;i  )
        {
            y=pow(-1,i)*pow(x,2*i);
        sum=sum y/((float)fact(2*i));
        }
    printf("using Maclaurin's series %.4f and original cosx=%.4f",sum,cos(x));

    }

}

int fact(int x)
{
    int prod=1;
    int i=1;
    for(i=1;i<=x;i  )
        prod=prod*i;
    return prod;
}

when I input 5(or any valid number) the results are quite weird like this

5
using Maclaurin's series -1.#IND and original cosx=0.2837

what is this -1.#IND?

CodePudding user response:

  1. You need function prototype before calling it.
  2. Add some ifs to check if you do not divide by zero.
  3. scanf returns number of successfully scanned elements. Check for 1 in this case.
            int fct = fact(2*i);
            if(fct) 
                sum=sum y/(double)fct;
            else
                {printf("DIVISION BY ZERO!!!!\n"); return 1;}

You will discover that int is to small for factorial function. Change it to double. Also, use double in all floating point operations.

double fact(int x);

int main()
{
    double sum,y;
    int x,i=0;
    double fct;
    while(scanf("%d",&x) == 1)
    {   sum=0;
        for(i=0;i<=N;i  )
        {
            y=pow(-1,i)*pow(x,2*i);
            fct = fact(2*i);
            if(fct != 0.0) 
                sum=sum y/fct;
            else
                {printf("DIVISION BY ZERO!!!!\n"); return 1;}
        }
        printf("using Maclaurin's series %.10f and original cosx=%.10f",sum,cos(x));
    }
}

double fact(int x)
{
    double prod=1.0;
    int i=1;
    for(i=1;i<=x;i  )
        prod=prod*i;
    return prod;
}

https://godbolt.org/z/qsh4qh3d1

  • Related