I was trying to rewrite a problem in my textbook using a loop. The book demonstrates e = 1 + 1/1! + ... 1/n!. I set up something similar with a for loop but the compiler in codeblocks does not like that exclamation point. Help!
#include <stdio.h>
#include <stdlib.h>
int main()
{
float e = 1, i;
int input;
printf("Enter the length you would like to approximate the value of e: ");
scanf("%d", &input);
for (i = 1; i <= input; i++)
{
e = e + 1.0/i!;
}
printf("e equals %f\n", e);
return 0;
}
It's not just Codeblocks, it's the whole c++ language that doesn't recognize this as a function. You'll need to write a function that does this for you.
Do something like:
1 2 3 4 5 6 7
int fact(int x)
{
int output = 1;
while (--x > 1)
output *= x+1;
return output;
}
It's not valid C when used that way. It's the not operator.
I'm not exactly sure what you're trying to do. Mathematically it would represent a factorial operation. Is that what you're trying to do there? Calculate the factorial of i?
@stewbond: That is just the integer factorial, but he needs a real factorial, for 1/2, 1/3, 1/4 etc.
somethig like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float e = 1, i;
int input;
printf("Enter the length you would like to approximate the value of e: ");
scanf("%d", &input);
for (i = 1; i <= input; i++)
{
e = e + 1.0/tgamma(i+1);
}
printf("e equals %f\n", e);
return 0;
}
Thanks for the help everyone, I got what I was going for using an additional function similar to what Stewbond posted ( thanks Stewbond ). At this point in the book I haven't used the math library yet but I'm sure it will be handy real soon.
This is what I came up with:
#include <stdio.h>
#include <stdlib.h>
double fact(double x);
int main(void);
int main(void)
{
double e = 1, input, i;
printf("Enter the length you would like to approximate the value of e: ");
scanf("%lf", &input);
for (i = 1; i <= input; i++)
{
e = e + 1/fact(i);
}
printf("e equals %f\n", e);
}