### Pi approximation

Hello,
Im trying to make a program to approximate pi when a certain number of values is input by the user. The more values, the more accurate. The equation is 4 * (-1^input)/(2n-1). I always end up with some weird number as the approximation, nowhere close to pi. Is there something wrong with my for loop?

 ```int _tmain(int argc, _TCHAR* argv[]) { int numberOfTerms; double sumOfTerms = 0, pi; char repeat; do{ cout << "Enter number of terms that should be considered in calculation of pi: "; cin >> numberOfTerms; for(int i = 0; i <= numberOfTerms - 1; i++){ sumOfTerms += (-1)^i / (2*i-1); } pi = 4 * sumOfTerms; cout << "*******************************************************" << endl; cout << "Considering " << numberOfTerms << " terms, the value of pi is: " << pi << endl; cout << "Do you want to repeat this program? (enter y to repeat): "; cin >> repeat; }while(repeat == 'y'); return 0; }```
`^` is the XOR operator. Is that what you meant?
Last edited on
Thanks for that, no i need to use pow(-1,i)
We'll you could, but that expression just flips from 1 to -1 and back. So just add or subtract the term for althernate iterations, don't call an O(n) algorithm to work that out.
Topic archived. No new replies allowed.