I'm working through an exercise to create a short program to calculate E using the series 1 + 1/1! +1/2! + 1/3! + ... The summation has to stop when value of a term is less than a value entered by the user.
The code I have to produce the basic factorial works fine when tested seperately, but when I run this code, it comes up with some very strange results for the factorials (1!, 2!, 3!, 4! etc come up as 0.5, 0.5, 1.5, 18 etc, instead of 1, 2, 6, 24 etc). This therefore goes on to give incorrect values for E.
The code as it is shows both the factorial and new value of E for each loop, which is what I want, but it doesn't show the correct figures.
Here is my current code:
#include <stdio.h>
#include <math.h>
/*
Program to find E to specified accuracy
*/
main()
{
int i,n;
float val,term,E,fac;
printf("What would you like to be the maximum value for the final term?\nPlease enter: ");
scanf("%f",&val);
term=1;
E=1;
fac=1;
for (n=1;(1/fac)>val;n=n+1)
{
for(i=1;i<=n;i=i+1)
{
fac = fac*i;
}
fac = fac/2;
printf("fac = %f\n",fac);
term = 1/fac;
printf("term = %f\n",term);
E=E+term;
}
printf("E = %f\n",E);
system("PAUSE");
}
I'm very new to C++, so any explanation or help that people could give would be much appreciated!