double expo = 1, term = 1 ;
int counter = 1 ;
while( term > 1.0e-16 ) // while term is not close to zero
expo += term ;
term /= ++counter ;
std::cout << "The estimated value of e is "
<< std::fixed << std::setprecision(12) << expo << '\n'
<< "The actual value of e is 2.7182818284590452353602874...\n" ;
constdouble e_actual = 2.7182818284590452353602874;
// factorial now declared within while loop
//double expo = 1, factorial = 1, counter = 0;
double expo = 1, counter = 0;
while (counter <=15)
counter = counter + 1;
int x1 = counter; // double not right here
double factorial = 1; // <== always start from 1
while (x1 > 1)
factorial = factorial*x1;
x1 = x1 - 1;
expo = expo + (1/factorial);
cout << setprecision(8); // only need to set this once
cout << "The estimated value of e is " <<expo << endl;
cout << "Whereas its actual value is " << e_actual << endl;
Now, clicking on the little cogwheel and running, I get:
The estimated value of e is 2.7182818
Whereas its actual value is 2.7182818
But, as JLBorges code shows you, you are doing more work than necessary recalculating the factorial each time. And slowing your program right down, too.
PS Code reads better when displayed using code tags!