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;
.
#include<stdio.h>
int main (void)
{
int n,i,j;
float e=1.0, nFact=1;
printf("please enter the number");
scanf("%d", &n);
for( i =1; i<= n ; i++)
{
nFact*=i;
e = e + (1.0/ nFact);
}
printf("The value of 'e' is : %f", e);
return 0;
}
Am i doing something wrong here?
You have forgotten to set the factorial variable to one. So, your variable is getting smaller quickly. This makes (1.0/nFact) even smaller and that is why you get smaller e.
nFact=1.0; //add this line so it resets to 1.0 everytime a factorial is needed
for( j = 1 ; j <= i; j++)
{
nFact *= j;
e = e + (1.0/ nFact);
}
//only single loop is more than enough
You are getting your factorial by O(n) complexity. Why not save the old value and use it in every iteration?(O(1)--->no need the factorial-loop. Just use old value since you are not resetting it. (Just multiply by i)
how can i get the proper output?
After the 11st or 12th iteration, your float
would not give enough precision-resolution-minimum step. Double
or BıgDecimal
seems better if your going for science.
That loop is very inefficient: Note how your inner loop computes the same thing over and over!
Instead, you should keep a running term and update it:
double term = 1;
double result = term;
for (unsigned int i = 1; i != n; ++i)
{
term /= i;
result += term;
}
printf("With %u steps we compute %f.\n", n, result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With