[try Beta version]
Not logged in

 
Function for finding Euler's Number

Feb 2, 2017 at 3:00pm
For some reason, when I execute the program, it'll always give me an answer close to "1.7". Can someone explain what's wrong with my program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

void sumOfFactorials(double);

int main()
{
    double e;
    cout<<"Enter the precision (e) for this sum: "<<endl;
    cin>>e;
    sumOfFactorials(e);
    system("pause");
    return 0;
}
void sumOfFactorials(double sum)
{
     int n=1, j=1;
     double e, f=1;
     
     for(n=1; ;n++)
     {
              f=1;
              for(j=n;j>=1;j--)
              {
                               f*=j;                     
              }
              if(1.0/f<e)
              {
                        break;                       
              }
              sum+=1.0/f;

     }
     cout<<"The sum is "<<sum<<"."<<endl;
     }
Last edited on Feb 2, 2017 at 3:08pm
Feb 2, 2017 at 3:20pm
You didn't initialise sum, so you missed the first term in the series. You are also getting confused about the function argument (which should be e, not sum, in the function declaration). You should return sum as a double from the function (not have a return type of void) and print the answer in the main loop.

It would be better to calculate the terms by a multiplier of the previous one, not a new factorial every time.

Although you can use a for loop for n in this way, a while loop might be better in this instance.


You should re-read my reply to your previous post and follow it carefully. This would have been better as a continuation of that thread, not a new thread.
Last edited on Feb 2, 2017 at 4:19pm
Topic archived. No new replies allowed.