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!

Recommended Answers

All 5 Replies

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.

Move your fac = 1; just before your factorial loop.

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);
    E=E+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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.