calculating "e"

Hi. I was trying to solve a question from c++ how to program book but I ran into problem with it. It says find the "e" number from an equation. but ijust get e = 2 from the program below. please help me find the problem.

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
  #include <iostream>
#include <string>
#include <iomanip>

using namespace std;
long long far(int);
void main()
{
	double e = 1;
	for (int i = 1; i <= 50; i++)
	{
		double addedValue = (1 / far(i));
		e += addedValue;
	}
	cout << "The e equals: " << e;
	cin >> e;

}

long long far(int i)
{
	if (i <= 1)
	{ 
		return 1;
	}
	else
	{
		return i * (far(i - 1));
	}
}
double addedValue = (1 / far(i));

You have a 'division by integer' issue here.

for example:

1
2
3
4
5
6
double result;

int top = 1;
int bottom = 8;   // for example, say

result = top/bottom;


the value of result will be zero as both numerator and denominator are both integers.

as a quick fix change
double addedValue = (1 / far(i));
to
double addedValue = (1.0 / far(i));

also line 16 you should be cout'ing your value of e to the screen, not cin'ing.
Last edited on
Thanks mutexe. actually I forgot to clear the last line( that was just for keeping the windows open so I could see the results.)
You're more than welcome mate.
If you want to keep the console open, see this sticky:
http://www.cplusplus.com/forum/beginner/1988/
Topic archived. No new replies allowed.