I am currently working on an exercise where I have to use the sum in the picture to approximate pi. . I have to prompt the user for an integer m which will be the number of terms used to do the calculation. I cannot use any functions from the math library.
I have written the following code so far:
#include <iostream>
using namespace std;
int factorial (unsigned int f );
double sum2 (unsigned int m );
double sum2 (unsigned int m=1 ){
double pi_half = 1.0;
for(int i = 1; i < m ; i++){
pi_half +=(factorial(i) /factorial(2.0 * i + 1)); /* compiler warning: narrowing conversion from 'double' to 'int' */
}
return (2*pi_half + 1 );
}
int factorial (unsigned int f ){
int fact =1;
for(int i= f ; i > 0 ; i--){
fact *= i;
}
return fact;
}
int main (){
unsigned int m{};
cin >> m;
cout << sum2(m);
return 0;
}
my idea was to create two functions: one to calculate the factorial and one to calculate pi. The factorial function on its own is working fine. When I call sum2 to however it is not working and I get a long exit code and the compiler warning I have indicated in the code. Could somebody tell my what my mistakes are?
Thank you in advance for your help!!