C

Asked • 05/04/19

Getting an incorrect output for e^x function I made for class, and getting the wrong number of terms?

So for my Intro to computer programming class we have to write 3 separate functions, one to calculate factorials, one to calculate powers (x^n), and one to calculate the number of terms of the taylor series with the given error approximation. Everytime I run my program, it prints that Nterms=1, instead of like 100, 300, 1000, etc. It's probably a simple error in my loop, but I can't locate it. Any help is appreciated! #include<stdio.h> #include<math.h> double power(float A, int B) {   double sum=1.00;   int nterms=1;     while ( nterms <= B && B > 0)   {    sum = A*sum;    nterms++;   }   return sum; } double factorial(int b) {   double fact=1.00;    while (b >= 2)   {    fact = b*(b-1)*fact;    b = b-2;   }     return fact;  } int Terms(float X, float a) {   int N=1,l;   double L,R;      while (L < a && a <= R)   { l=N+1;    L= (power(X,l)/(factorial(l)));    R= (power(X,N)/(factorial(N)));    N++;  }     return N; } int main() {     float x, delta; double sum=0.00, term=0.00;   int n, Nterms;     printf("Please enter a decimal number. x=");   scanf("%f",&x);   printf("Please enter an another number. delta=");   scanf("%f",&delta);     Nterms=Terms(x,delta);   printf("Nterms=%d\\n",Nterms);     for(n=0;n<Nterms;n++)   {    if( n==0 || n==1 )    {     sum = 1 + x;    }    else    {     sum = sum + term;     term = (power(x,n))/(factorial(n));    }    }    printf("The approximation for e^(%f)=%.4f",x,sum);     return 0; }

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.