Hi everybody, here i am again ¬¬,
I am doing an exercise that ask me to write a program to calculate this constant:
e = 1 + 1/1! + 1/2! + 1/3! ...
The user need to input how much the program must calculate.
I wrote this code, but i am not sure that the result is right, i just want to confirm that it is ok.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int nFactorials;
int cNumber;
int power = 1;
double cFactorial;
int counter = 1;
double e;
cout << "This program calculates this constant -> e = 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ..." << endl;
cout << "Type the precision as an integer: ";
cin >> nFactorials;
e = 1;
while ( counter <= nFactorials )
{
cNumber = nFactorials - nFactorials + counter;
cFactorial = cNumber * ( cNumber - power );
power++;
while ( power < cNumber )
{
cFactorial = cFactorial * ( cNumber - power );
power++;
}
power = 1;
if ( cFactorial > 0 )
e += 1 / cFactorial;
counter++;
}
cout << "Constant result: " << e << endl;
return 0;
}
Here is some results:
% ./b
This program calculates this constant -> e = 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ...
Type the precision as an integer: 2
Constant result: 1.5
% ./b
This program calculates this constant -> e = 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ...
Type the precision as an integer: 3
Constant result: 1.66667
% ./b
This program calculates this constant -> e = 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ...
Type the precision as an integer: 4
Constant result: 1.70833
Is it ok?
Thanks.