C Find the value of e The approximate value of e is determin
C++
Find the value of e
The approximate value of e is determined as 1 + 1/1! + 1/2! + 1/3! + 1/4! + ... + 1/n! with an error less than 1/n!.
Write a program to input the allowed error value. Use that value to find n, and then use that n to find the approximated e value.
Input example: 0.0002
Output example: 2.71825
Solution
// C++ code
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
#include <stdlib.h> /* srand, rand */
#include <iomanip>
#include <limits.h>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int factorial(int n)
{
int fact = 1;
for (int i = 2; i <= n; ++i)
{
fact = fact * i;
}
return fact;
}
int main()
{
double error;
cout << \"Enter the allowed error: \";
cin >> error;
double sum = 1;
int i =1;
double value = 0;
while(true)
{
value = sum;
sum = sum + 1.0/factorial(i);
i++;
if(sum-value < error)
break;
}
cout << \"Approximate value of e: \" << sum << endl;
return 0;
}
/*
output:
Enter the allowed error: 0.0002
Approximate value of e: 2.71825
*/

