About Calculating Pi - C++ Forum

cplusplus.com
  • TUTORIALS
  • REFERENCE
  • ARTICLES
  • FORUM

C++

  • Tutorials
  • Reference
  • Articles
  • Forum

Forum

  • Beginners
  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Lounge
  • Jobs
  • Forum
  • Beginners
  • About calculating pi

About calculating pi

e490012662 (1) 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: pi = 4 [ 1 - 1/3 + 1/5 - 1/7 + 1/9 . . . + ((-1)^n)/(2n + 1) ] 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!
1234567891011121314151617181920212223242526272829303132333435 #include <iostream> #include <cmath> using namespace 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; }
Last edited on Renthalkx97 (152) You have the formula typed incorrectly. It should be (-1)k + 1 / (2k -1) Or in code 4 * (pow(-1, i + 1.0)) / (2 * i - 1)) Last edited on Renthalkx97 (152) No it doesn't. You're simply fixing the incorrect output by adding 3. Last edited on Topic archived. No new replies allowed. Home page | Privacy policy© cplusplus.com, 2000-2026 - All rights reserved - v3.3.3Spotted an error? contact us

Tag » Approximate Value Of Pi C++