I was assigned a homework project that's starting to get annoying. I can't figure out what's going wrong with it. Here's the question:
The number Pi may be calculated using the following infinite series:
Pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... )
How many terms of this series you need to use before you get the approximation p of Pi, where:
a)p = 3.0
b)p = 3.1
c)p = 3.14
d)p = 3.141
e)p = 3.1415
f)p = 3.14159
Write a C++ program to answer this question.
My answer is always 4 and my term starts at 0 and stays at 1. Here's what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
double pif(double); //Fucntion to determine value of pi
int term; //Variable to count terms
int main()
{
cout << "Value of Pi" << " " << "Number of terms" << endl;
cout << pif(3.0) << " " << term << endl;
cout << pif(3.1) << " " << term << endl;
cout << pif(3.14) << " " << term << endl;
cout << pif(3.141) << " " << term << endl;
cout << pif(3.1415) << " " << term << endl;
cout << pif(3.14159) << " " << term << endl;
return 0;
}
double pif(double n)
{
double pi = 0.0; //Variable to store value of pi
int sign = 1; //Variable to store sign
bool check = false; //Variable to check value of pi
term = 0;
while (!check)
{
if (pi * 4.0 >= n) //If value of pi is greater than or equal to approx of pi
check = true; //Then exit the loop
else
{
pi *= sign * (1.0 / (1.0 + term * 2.0)); //Otherwise calculate value of pi
sign *= -1; //Change sign
++term; //And increment term
}
}
pi *= 4.0; //Perform final pi calculation after fractional sums have been determined
return pi;
}
Thanks for the help!