/* The constant e, which is about 2.718, may be defined by the series e = 1/(0!) + 1/(1!) + 1/(2!) + 1/(3!) + 1/(4!) ... Here n! is n factorial, which is n*(n-1)*(n-2)...(3)(2)(1) for n a positive integer. 0! is defined to be 1. This program computes e as the sum of the series up to the 1/(12!) term, which should be accurate to about 9 decimal places. Factorial is implemented as a function. */ #include #include unsigned long int factorial(int); void main(){ double e=0; for (int n = 0; n <= 12; n++) { e += 1./(factorial(n)); /* cout << "main func, n = " << n << endl; */ } cout << "e is approximately " << setiosflags(ios::fixed|ios::showpoint) << setprecision(9) << e << ".\n"; } unsigned long int factorial(int n){ /* Note that the variable n is changed in this function. This only changes the copy of the variable made inside this function (since we are using call by value. The n variable in the main function is unchanged by the action of this factorial function. */ unsigned long int fact = 1; while (n >= 1){ /* cout << "factorial function, n = " << n << endl; */ fact *=n; n--; } return fact; }