fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. int main() {
  6.  
  7. const double PI = 3.141592;
  8. int n, sign = 1;
  9. double sum = 0,test,m;
  10.  
  11. cout << "This program determines how many iterations of the infinite series for\n"
  12. "pi is needed to get with 'n' decimal places of the true value of pi.\n"
  13. "How many decimal places of accuracy should there be?" << endl;
  14. cin >> n;
  15.  
  16. double p = PI * pow(10.0, n);
  17. p = static_cast<double>(static_cast<int>(p) / pow(10, n));
  18. int counter = 0;
  19. bool stop = false;
  20.  
  21. for (double i = 1;!stop;i = i+2) {
  22. sum = sum + (1.0/ i) * sign;
  23. sign = -sign;
  24. counter++;
  25. test = (4 * sum) * pow(10.0,n);
  26. test = static_cast<double>(static_cast<int>(test) / pow(10, n));
  27. cout << "" ;
  28. if (test == p)
  29. stop = true;
  30. }
  31. cout << test << '\n';
  32. cout << "The series was iterated " << counter<< " times and reached the value of pi\nwithin "<< n << " decimal places." << endl;
  33. return 0;
  34. }
Success #stdin #stdout 0s 3464KB
stdin
4
stdout
This program determines how many iterations of the infinite series   for
pi is needed to get with 'n' decimal places of the true value of pi.
How many decimal places of accuracy should there be?
3.1415
The series was iterated 10794 times and reached the value of pi
within 4 decimal places.