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

      int i,n;
      float val,term,E,fac;
      printf("What would you like to be the maximum value for the final term?\nPlease enter: ");
      for (n=1;(1/fac)>val;n=n+1)
                fac = fac*i;
         fac = fac/2;
         printf("fac = %f\n",fac);
         term = 1/fac;
         printf("term = %f\n",term);
      printf("E = %f\n",E);

I'm very new to C++, so any explanation or help that people could give would be much appreciated!

7 Years
Discussion Span
Last Post by lil_miss_choc

Why are you dividing the factorial by 2 in line 23?

Also, you don't reset the factorial value each time through the n loop, so in the i loop it remultiplies the values 1 through n-1 to the previous factorial.


Thank you for responding so quickly!

For some reason, when I tested the code, it kept coming up with double the correct number for the factorial. It did it consistently for any number I tried, so I just divided the end result by two.

How would I go about correcting the factorial value? Please forgive my woeful ignorance - we were given exercises in C++ after learning Matlab, with very little in the way of explanation of how C++ works.


I'd redo the loop section

for (n=1;(1/fac)>val;n=n+1) {      
    fac = fac*n;
    printf("fac = %f\n",fac);
    term = 1/fac;
    printf("term = %f\n",term);

You could do what WaltP said, but then you'd be recalculating the entire factorial each time. It will get really slow really fast. My code just keeps the old value and adds the new term each time.

Edited by Momerath: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.