Help with While Loop program

I have an assignment where we are told to estimate the value of e using the formula e= 1 + 1/1! + 1/2! + 1/3!...

my code runs but, I can't seem to get the right decimal value for e. I can't identify what I am doing wrong. Is it the way I initiated my variables?? Any help is appreciated.

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


int main()
{

double expo = 1, factorial = 1, counter = 0;

while (counter <=15)
{
counter = counter + 1;
double x1 = counter;


while (x1 > 1)
{
factorial = factorial*x1;
x1 = x1 - 1;
}

expo = expo + (1/factorial);
}

cout << "The estimated value of e is " << setprecision(5) <<expo << "\n" << endl;


system("PAUSE");

return 0;



}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>

int main()
{
    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" ;
}

http://coliru.stacked-crooked.com/a/ffa6e75669bd228b
Last edited on
The problem with your code is that you are not resetting your factorial value back to 1 before you recalculate it using your inner while loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <iomanip>
using namespace std;

const double e_actual = 2.7182818284590452353602874;

int main()
{
    // 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;

    return 0;
}


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.

Andy

PS Code reads better when displayed using code tags!

How to use code tags
http://www.cplusplus.com/articles/jEywvCM9/

How to use tags
http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
Topic archived. No new replies allowed.