Cannot achieve correct output.

I am working on a project that requires me to write a program that calculates the e approximation (1 + x+ x^2/2! + x^3/3! +x^4/4! + ...). I have the program running, but I cannot get it to output correctly when I run it.

Here is the output needed with sample numbers(This program approximates e^x using a n-term power series expansion.
Enter the value of x>1
How many terms do you wish to use in this approximation?5
e^1 = 1 + 1 + 0.5 + 0.166667 + 0.0416667 = 2.70833333333333303727
The exact value of e^1.00000000000000000000 is 2.71828182845904509080.
Approximation error is 0.00994849512571205352.).

This is the output I am getting(This program approximates e^x using a n-term power series expansion.
Enter the number of terms : Expected value : 2.71828182845905
The exact value of : 1
Approximation error is : 1.71828182845905).


Here is the program I currently have:

#include <stdio.h>
#include <math.h>

#define MAX_LINE_LEN 80

double factorial(unsigned);

int main(int argc, char *argv[]) {
unsigned n,x;
long double e1 = 1.0;
char line[MAX_LINE_LEN];

printf("This program approximates e^x using a n-term power series expantion.");
printf("Enter the number of terms : ");
fgets(line,MAX_LINE_LEN,stdin);
if ((sscanf(line,"%u",&n) != 1) && (n > 0)) {
puts("\ninvalid input\n");
return -1;
}

for (x = 1; x < n; x++) {
e1 += (double)1.0 / factorial(x);
}


printf("Expected value : %.15g\n",exp(1.0));
printf("The exact value of : %.15LG\n",e1);
printf("Approximation error is : %.15g\n",fabs(exp(1.0) - e1));

return 0;
}

double factorial(unsigned n) {
if (n == 1) return n;
return n * factorial(n-1);
}


If anyone could help me understand how to get the correct output that would be awesome!!

Thanks for your help and time.
Topic archived. No new replies allowed.