This is what I came up with:
#include <stdio.h>
int main (void)
{
int n, i, j;
float e = 1.0, nFact = 1.0;
printf ("please enter the number");
scanf ("%d", &n);
for (i = 1; i <= n ; i++)
{
for (j = 1; j <= i; j++)
{
nFact *= j;
}
e = e + (1.0 / nFact);
}
printf ("The value of 'e' is : %f", e);
return 0;
}
This is what I get from this code.
Input: 3
Output: 2.58333 (which is close to 2.6666…)
But for n=3, e should give 2.6666.. as a value.
Am I doing something wrong here? How can I get the proper output?
You are needlessly calculating the factorial in every iteration. Just replace the inner loop by
nFact *= i;.