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.