Converting my program into a function

Okay, so I've been trying to figure out how to turn my program into a function, but I don't know a clear and concise way to do it. Could someone please show me how to do it? It involves using things such as: void/void NameOfFunction(int,int). Things like that. This is the question. Calculate the sum Sn = 1 + 1/1! + 1/2! + 1/3!+...+1/n! with precision ε (1/n!<ε), using a function. I already have my program written down below.

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
#include <iostream>
using namespace std;
int main(){
    int n=1, j=1;
    double e, f=1, sum=1;
    cout<<"Enter the precision (e) for this sum: "<<endl;
    cin>>e;
    
    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;
system("pause");
return 0;
}
Last edited on
Your input is the precision (e or epsilon) and the output is the sum, which happens to be Euler's number, e, the base of natural logarithms. So I would have function prototype
double Euler( double epsilon );

However, this is not a good way of computing it.
(1) Factorials grow too fast for this to work.
(2) Each term is simply related to the previous one - you shouldn't compute it from scratch. i.e.
first term =1;
next term = last term/1.0;
next term = last term/2.0;
next term = last term/3.0;
Spot the pattern?
Last edited on
Topic archived. No new replies allowed.