Aprroximating e with recursion.

Hello,
I am trying to get my program to approximate e by adding up terms:
(1/1!)+(1/2!)+(1/3!)+(1/4!)+...

I have to do it using recursion. I cant figure out why something would be wrong right now.
When I run it it reads out:

Enter number: 5
k is 1 sum is 1
k is 0 sum is 1
k is 0 sum is 1
k is 0 sum is 1
k is 0 sum is 1
e approximated to the 5th term is: 1

Help appreciated.

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
35
36
37
38
39
40
41
42
#include <iostream>
#include <iomanip>
using namespace std;

unsigned long factorial(unsigned long);

int main()
{


	int n;
	double k, sum = 0;
	cout << "Enter number: ";
	cin >> n;

	for (double counter = 1; counter <= n; counter++)
	{
		k = (1 / (factorial(counter)));

		cout << "k is "<< k << " ";

		sum = sum + k;

		cout << "sum is " << sum << endl;

	}

	cout << "e approximated to the" << n << "th term is: " << sum << endl;


	system("pause");

	return 0;
}

unsigned long factorial(unsigned long number)
{
	if (number <= 1)
		return 1;
	else
		return number*factorial(number - 1);
}
Last edited on
e= 1 + 1/1 + 1/(1*2) + 1/(1*2*3) + ....
http://en.wikipedia.org/wiki/E_%28mathematical_constant%29

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
#include <iostream>
using namespace std;

unsigned long factorial(unsigned long number)
{
	if (number <= 1) return 1;
	else return number*factorial(number - 1);
}


int main()
{
	int n=9;
	double k, sum = 0;

	for (int counter = 0; counter <n; counter++)
	{
		k = 1.0 / (factorial(counter));
		cout << "k is "<< k << " ";
		sum = sum + k;
		cout << "sum is " << sum << endl;
	}
	cout << "e approximated to the" << n << "th term is: " << sum << endl;

return 0;
}


notice, in this code, factorial is calculated by recursion. not e.
Topic archived. No new replies allowed.