Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 5.19 Calculating the Value of pi
- Deitel & Deitel C++ How to Program, 10th ed (Indian subcontinent adaptation)
- Visual Studio Community 2019
- Objectives:
- 1.) display a table of pi approximations from 1st term in sequence to the 200,000th term
- 2.) indicate the number of terms needed to arrive at the first result containing '3.14159'
- */
- #include <iostream>
- #include <iomanip>
- using namespace std;
- double const NUM = 4.0;
- int main(void) {
- double test{ 4.0 }, denom{ 3.0 };
- int answer;
- int count{ 1 };
- bool isNegative = true;
- int foundIt = 0; // first time '3.14159' pops up foundIt is set to the count
- while (count <= 200000 ) {
- if (isNegative) {
- test -= (NUM / denom);
- isNegative = false;
- }
- else {
- test += (NUM / denom);
- isNegative = true;
- }
- if (foundIt == 0) {
- answer = (int)(test * 100000); // convert to an integer for comparison
- if (answer == 314159) foundIt = count;
- }
- denom += 2;
- cout << count << ": " << setprecision(12) << test << "\n";
- count++;
- }
- cout << "It took " << foundIt << " terms to get the first occurrence of 3.14159\n";
- cout << "Note: This does not take into account the initial term of '4' in the sequence.\n";
- return 0;
- }
Add Comment
Please, Sign In to add comment