I'm having trouble I cant get it to output the correct value for pi and its driving me crazy what am I doing wrong?
The program is giving me the the final value for pi for all iterations. I think it is my loop. here's what I have so far
just in case this is a sample of the output I'm getting
-----------------------------------------------------------------------
1.pi = 3.339682540 // it should be 4.000000000
2.pi = 3.339682540 // 2.666666666
3.pi = 3.339682540 // 3.466666667
4.pi = 3.339682540 // 2.895238095
5.pi = 3.339682540 // 3.339682540
Final pi = pi = 3.39682540
-----------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//function to read inputs from the user test for proper input
int validInput (string prompt)
{
int yourResponse = 0;
cin >> yourResponse;
cout << endl;
while (yourResponse < 1)
{
cout << "Error, cannot be 0 or negative, please try again" << endl;
cin >> yourResponse;
cout << endl;
}
return yourResponse;
}
int main()
{
double pi = 0;
int numTerms = 0;
int yourResponse = 0;
int steps = 0;
string userInput = "Please enter the number of terms to use: ";
string userOutput = "Display Pi after how many steps ? ";
cout << "This program will approximate the value of PI " << endl << endl;
cout << userInput;
numTerms = validInput (userInput);
cout <<endl;
cout << userOutput;
steps = validInput (userOutput);
cout << endl;
// Calculating pi here is where I think I messed up
for (double n = 1; n <= numTerms; n++)
{
pi += (double) pow(-1, n+1)/(2*n-1);
}
pi *= 4;
cout << fixed << showpoint << setprecision(9);
cout << "RESULTS: " << endl;
for(int i = 1; i <= numTerms; i ++) //to display steps
if(i % steps == 0)
{
cout << i <<": " << "Pi = " << pi << endl << endl;
}
cout << endl;
cout << "Final Pi = " << pi << endl;
cout << endl << endl;
system ("PAUSE");
return 0;
}
|