/*********************************************
Approximating e by series expansion
Using the formula:
e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ...
Write a program that takes a number of terms
from the user and prints out the approximation
of e given by that number of terms
*********************************************/
#include <stdio.h>
int factorial(int n);
/*********************************************
** main() function
*********************************************/
int main() {
// Get n, the number of terms, from user
int n;
printf("How many terms in the series expansion? ");
fflush(stdout);
scanf(" %d", &n);
// Compute and sum n terms of series
double e = 0;
for(int i=0; i < n; i++) {
e += 1.0/factorial(i);
}
// Print approximation to screen
printf("e is approximately %.20f\n", e);
return 0;
}
/*********************************************
** factorial - Does what you think!
*********************************************/
int factorial(int n) {
int ans = 1;
for(int i = 2; i <= n; i++) {
ans = ans*i;
}
return ans;
}