We were assigned the following problem as a large project in my Freshman intro to C++ programming class:
We have to determine the number of terms needed to calculate Pi to a specific number (3.0, 3.1, 3.14, 3.141, 3.1415, and 3.14159), using the formula:
pi= 4(1-1/3+1/5-1/7+1/9-1/11+1/13...)
I thought I had the code figured out pretty easily, but I have having a problem. I was going to use the following (incomplete) code as a model:
// Date: 10/30/06
// Homework #07
// Student: Jim Hummel
// Course: CSE 121
// This program calculates the number of terms required for an approximation of pi.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double pif(double q);
int terms=0;
int main()
{double q=3.1;
cout << "Pi Value Terms\n--------------------------\n";
cout << fixed << setprecision(2);
cout << pif(q)<< " "<< terms << endl;
return 0;
}
double pif (double q)
{double n=1.0;
double pi=0;
while (pi<(q-(1.0/q)) && pi>(q+(1.0/q)))
{
pi = pow(-1.0,n)/(2.0*n-1.0);
n++;
terms++;
}
pi*=4.0;
return pi;
}
In the main function there, I was going to try to have it call the function pif() once for each value q that I set to it, then cout the results, and the number of terms.
I've been toying around with possible options (as seen in the while statement there), but no matter what I do, it returns a value of o terms and 0.00 for pi each time.
What am I doing wrong?
Thanks in advance, this is killing me.