0

I am trying to make a program in C that uses a recursive function to calculate the factorial for Euler's number, and sends that data to main where the recursive function is to stop once two successive values have a difference of 0.0000001, however i cannot seem to get my program to work as it keeps returning -inf. Anyone know what im doing wrong? EDIT: With this current code i can get the program to print result as 0.5, but it does not increment n past 2.

#include <stdio.h>
double factorial(double n);

int main ()
{
  double n;
  double sum = 0;
  double last;
  double result = 0;
  for (n = 1; result <=0.0000001; n++)
  {  
    last  = sum;
    sum = factorial(n);
    result  = (1 / last) - (1 / sum);
    printf("result is %lf\n", result);
  }
  printf("result is %lf\n", result); // troubleshooting
  return 0;
}

double factorial(double n)
{
  if (n > 0)
    return ( n * factorial(n-1));
  else
    return 1;
} 
T.Steele
  • 1
  • 1
  • 2

1 Answers1

2

On the first iteration in main:

sum == 0
last = sum; => last == 0
result  = (1 / sum) - (1 / last); => 1 / last == 1 / 0 == inf

Then you subtract (1 / last), which is inf, from (1 / sum), and get negative infinity.

Also, the loop never iterates more than once because you return result on the very first iteration.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • I removed the return in the for loop, however im still stuck on getting n to increment and return the value to sum as i keep getting 0 or -inf depending on the value that i initialize n at – T.Steele Feb 16 '19 at 16:26
  • At the moment, your current code doesn't initialise `n` at all. Also, as long as `last == 0` on any iteration of the loop, you're going to get negative infinity. – ForceBru Feb 16 '19 at 16:28