Michael Ali - 1 year ago 225
C++ Question

# C++ Program to Calculate e constant using loops

I was asked to create a simplistic program to calculate e by asking for a value i (degree of accuracy) and then using the formula 1 +1/1! + 1/2! + 1/3! + ⋯ + 1!
I am getting a very close value but it is still not correct. Where did I go wrong, and what are ways to improve the code?

``````#include <iostream>
using namespace std;

int main()
{
double e=0.0;
double factorial=0;
int i=0;
int j,k=0;//counter variables

cout<<"Enter degree of accuracy: ";
cin>>i;

for(j=0;j<=i;j++)    //for loop to calculate 'e'
{
factorial=1;     //To reset factorial to 1 for every value of j
for(k=1;k<=j;k++)//for loop to calculate factorial
{
factorial*=k;
}
e+=(1/factorial);
}
cout<<"Value for e given i: "<<e<<endl;

system("pause");
return 0;
}
``````

2. You are doing a lot more work computing the factorial than you need to do. Each time through the outer loop, you need to compute the factorial of `i`, but (other than the first time) you've just finished computing the factorial of the previous value (`i-1`). So rather than resetting `factorial` to 1 and running through the inner loop, just multiply the previous factorial value by `i` and your done. (Oh, and initialize `factorial` to 1 instead of 0 at the start of the program.)