Reputation: 1019
I'm working on an assignment in a first year C class and we are in the loop section of a textbook. I've already learned a few languages but I believe I am doing this wrong somehow since I am not getting the correct output. I believe I need to do this question using loops (so no additional math libraries). Normally I'd use a debugger, but I'm programming C using sublime text and the command prompt so I don't think that's possible. We also have not gone through methods/functions/whatever C uses yet, so my solution can't use that stuff.
Using only C89 is preferred.
Here is the question:
The value of the mathematical constant e can be expressed as an infinite series: e = 1 + 1/1! + 1/2! + 1/3! + ... Write a program that approximates e by computing the value of 1 + 1/1! + 1/2! + 1/3! + ... + 1/n! where n is an integer entered by the user.
Note that I believe ! in this case means factorial.
I'm checking my output against that of this sigma calculator, and just adding 1 to the calculator's output to check if my result is correct or not.
http://www.mathsisfun.com/numbers/sigma-calculator.html
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float e = 1;/* Start off as 1 since the equation adds 1 anyways */
int input, i, j;
/* Ask the user for the value that they want to use, and store it in a variable */
printf("Enter an integer to use to approximate: ");
scanf("%d", &input);
for (i = 1; i < input; i++)
{
/* This inside loop is for the factorial, where j goes through all of the factorials for each i */
for(j = i; j > 0; j--)
{
e += (1/(float)j);
}
}
printf("e equals %f\n", e);
return 0;
}
Upvotes: 0
Views: 4140
Reputation: 869
The loop should be this way:
for(i=1; i<=input; i++)
{
int result = 1;
for(int j=1; j<=i; j++)
{
result = result * j;
}
//now the "result" is the factorial of i
e += 1 / (float)result; // 1/factorial(1) + 1/factorial(2) + ...
}
Upvotes: 4
Reputation: 3295
The loop can be simple enough like this :
int fact = 1 ;
for(int i = 1; i < input; ++i)
{
fact *= i ;
e += (1.0f/(float)fact);
}
No nested loop is required. Here is a working version.
Upvotes: 2
Reputation: 1545
You are not doing the right thing in your factorial calculation. Your are summing when you should be multiplying. Your inner loop should probably look like this :
/* This inside loop is for the factorial, where j goes through all of the factorials for each i */
float inverse_factorial_i = 1;
for(j = i; j > 0; j--)
{
inverse_factorial_i *= (1/(float)j);
}
And then
e += inverse_factorial_i
Upvotes: 2
Reputation: 36431
No your code just makes sums over i of sums over j in [1,i] of 1/j. So you calculates 1/1 + (1/1+1/2) + (1/1+1/2+1/3) + ... and not 1/1 + (1/1*1/2) + (1/1*1/2*1/3) + ...
That should be something like:
for (i = 1; i < input; i++)
{
float inversefact = 1;
for(j = i; j > 0; j--)
{
inversefact *= (1/(float)j);
}
e += inversefact;
}
Upvotes: 1