The factorial of a non-negative integer n (written n! and read n factorial) is defined by
n! = 1 ,if n = 0 or 1
= 1*2*3*....n, if n > 1
So for instance, 3! = 1* 2 * 3 = 6 and 5! = 1 * 2 * 3 * 4 * 5 = 120 etc.
The number e the natural base of the exponential function is defined as
e = 1/0! + 1/1! + 1/2! + 1/3! + ....1/n!+ .....
Write a program that estimates the value of e using the first few terms up to 1/n!, that is
e = 1/0! + 1/1! + 1/2! + 1/3! + ....1/n!
The user is asked for the value of n, then compute the above sum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main() {
int n, i;
long nfact=1;
cout << "n=";
cin >>n;
if ( n >0 )
for ( i = 1;i <=n;i++)
nfact += 1.0/i // im confused here.
cout << "n!= "<< nfact;
this is all i got so far or is my code entirely wrong ?
#include <iostream>
usingnamespace std;
int main() {
int n,i;
cout << " Enter n=";
cin >> n;
double e=0;
int denominator=1;
for (int i=0; i < n;i++)
{
e+=1.0/ (denominator *= i+1 );
cout <<"The sum is " <<e;
}
return 0;
}
i dont think the code is right cuz i keep getting numbers that are bigger than what it's supposed to be ( type in n=2, turns out to be 11.5)
and i keep getting "The sum is" multiple times.
Nope I just checked my formula is correct ( according to what he said ) except for one thing. He gave me the wrong formula he said the first value was 1/0! and idk for some reason I was thinking it was = to 0 but thats undefined..the real formula for find e is 1 + 1/1 , + 1/2 + 1/3 + 1/n.. The reason you got 11.5 for 2 idk you must have outputted a one first on accident.
I fixed the formula by changing intial value of e to 1 and I moved the denominator *= outside of the e += to make it look neater.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
constint n = 20;
double e = 1.0;
int denominator = 1;
for( int i = 0; i < n; ++i )
{
denominator *= i + 1;
e += 1.0 / denominator;
}
std::cout << e << std::endl;
}
Cheers.
Oh and you are getting the sum is multiple times because you have it inside of the for loop.