1

I want to calculate the result of this formula:

1/1! + 1/2! + 1/3! + 1/4! + ... + 1/10!

Here is my code:

#include <iostream>
#include <cstdlib>
using namespace std;

double func(int );

int main(void) {
int a;
double sum=0;
do{
    cout << "input a num: " ;
    cin >> a;

}while (a<=0);

for (int i=1; i<a+1; i++) {
    sum = sum + (double)(1/func(i));
}
    cout << sum << endl;
    return 0;
}

double func(int num)
{
    if(num>0)
        return num*func(num-1);
    else
        return 1;
}

I am curious about why I have to use double type for func to pass back. If I used int type to pass, like this

int func(int num)

The result of sum will be not correct.

haogroot
  • 35
  • 5

1 Answers1

1

That would work. Infact, you don't need the typecast (double)(1/func(i))

Change the line as follows:

 sum = sum + (1.0/func(i));
Pooja Nilangekar
  • 1,419
  • 13
  • 20