Hoi!
I'm supposed to get the value of e by summing 1 and the inverse of factorials from 1 to 5 (i.e. e = 1 + 1/1! + 1/2!+...+1/5!). I edited the code and now I get "The value of e is approximately 134513785."
#include<stdio.h>
int main(void)
{
int e, x, y;
double factorial;
for (x=5; x>=1; x--)
{
for (y=5; y>=1; y--)
{
factorial *= y;
}
x = 1/factorial;
}
e += 1 + x;
printf("The value of e is approximately %d.\n", e);
return 0;
}
and then with the following code i get "The value of e is approximately equal to 0."
#include<stdio.h>
int main(void)
{
int e, x, y;
double factorial;
for (x=5; x>=1; x--)
{
for (y=5; y>=1; y--)
{
factorial *= y;
}
x = 1/factorial;
}
e = 1 + x;
printf("The value of e is approximately %d.\n", e);
return 0;
}
#include<stdio.h>
int main(void)
{
int e, x, y;
double factorial;
for (x=5; x>=1; x--)
{
for (y=5; y>=1; y--)
{
factorial *= y;
}
x = 1/factorial;
}
e = 1 + x;
printf("The value of e is approximately %d.\n", e);
return 0;
}
after slightly reformatting you code, I cannot understand how the x loop will run more than once
i think i said incorrectly, i don't mean that the x loop will run more than once, but because i get such a large value (134513785), i thought that it was because when the next value for x is computed, the factorial of the previous value of x adds to the factorial of the next value.
With c++ when you initialize a variable it is almost always set to zero. What probably happened is that you did 1/0 and the program just did something with it, also 1/factorial will most likely be a float less than 1.
you are very close to find the solution, just follow carefully @smilodon's hints. Focus on your factorial - let's say you have to count 5! which is 1*2*3*4*5. How to implement it now?
1 2 3
double factorial = 1;
for(int i = 1; i <= 5; i++)
factorial *= i;
Now compare it with your code - notice, you're computing the factorial using an extra loop, which gives you a false result (n! powered by n if I count correctly)
any conclusion? i guess you already have done it...
Another hint is concerning the Euler's number (e). According to the formula, e=
----
\
/ 1/n! where n€<0,+inf) or just 1+ 1/n! (n€<1,+inf) since 0! = 1)
----
in that case we can assign value of "1" to our e number, here we go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
double factorial = 1;
double e = 1; //we will add only 1/n!, since 1 is already assigned
for(int i = 1; i <= N; i++) //change N to any number, greater N == better approximation
{
factorial *= i; //computing the factorial
e += 1/factorial; // 1 is already assigned
}
cout<<setprecision(14)<<e; // for s.p.(14) e = 2,718281828459
return 0;
}