garryhtreez

5.19

Nov 20th, 2020 (edited)
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. /* 5.19 Calculating the Value of pi
  2.     Deitel & Deitel C++ How to Program, 10th ed (Indian subcontinent adaptation)
  3.     Visual Studio Community 2019
  4.  
  5.   Objectives:
  6.   1.) display a table of pi approximations from 1st term in sequence to the 200,000th term
  7.   2.) indicate the number of terms needed to arrive at the first result containing '3.14159'
  8.  */
  9.  
  10. #include <iostream>
  11. #include <iomanip>
  12.  
  13. using namespace std;
  14. double const NUM = 4.0;
  15.  
  16. int main(void) {
  17.     double test{ 4.0 }, denom{ 3.0 };
  18.     int answer;
  19.     int count{ 1 };
  20.     bool isNegative = true;
  21.     int foundIt = 0; // first time '3.14159' pops up foundIt is set to the count
  22.  
  23.     while (count <= 200000 ) {
  24.         if (isNegative) {
  25.             test -= (NUM / denom);
  26.             isNegative = false;
  27.         }
  28.         else {
  29.             test += (NUM / denom);
  30.             isNegative = true;
  31.         }
  32.         if (foundIt == 0) {
  33.             answer = (int)(test * 100000); // convert to an integer for comparison
  34.             if (answer == 314159) foundIt = count;
  35.         }
  36.         denom += 2;
  37.         cout << count << ": " << setprecision(12) << test << "\n";
  38.         count++;
  39.     }
  40.     cout << "It took " << foundIt << " terms to get the first occurrence of 3.14159\n";
  41.     cout << "Note: This does not take into account the initial term of '4' in the sequence.\n";
  42.     return 0;
  43. }
Add Comment
Please, Sign In to add comment