Hi guys! I am new to C++ and I am taking a C++ class in college now. My professor gave us a hw and the problem is "An approximate value of pi can be calculated using the series given below:
Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation."
I am so lost so I search online for that code and I tried to understand the code and add and delete the thing that I need/don't need.(I will try to write my own code after I understand the whole thing) I understand most of them but when I get to "pi += 4 * (pow(-1,i))/((2*i)+1);" and "pi += 3;" then I am lost. Can anyone explain to me why I need to set the variable "i" = 1 first and why I have to add 3 and pi together after that for loop?
I would appreciate if anyone can help me on this. Thanks!
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int terms;
double pi = 1;
{
cout << "Input the number of terms to approximate pi to." << endl;
cin >> terms;
if (terms > 0)
{
// The series approximates to the value terms times
for (int i = 1; i <= terms; i++)
{
pi += 4 * (pow(-1,i))/((2*i)+1); //
}
// Once loop is complete, add 3 for final pi value
pi += 3;
cout << "The approximated value of pi is: " << pi << "." << endl << endl;
}
// Stop the program if the user enteres an invalid value.
else cout << endl << "You did not enter a valid value.\n" << endl;
}
return 0;
}