84.5k views
3 votes
You've been hired by Fruity Fillers to write a C++ console application that approximates PI. Use a validation loop to prompt for and get from the user the number of terms to approximate PI to that is between 1 and 10,000. Use the following Leibniz formula: PI approximation = 4 * (1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...) The terms appear within the parentheses in the formula. A PI approximation to ... • One term is 4 * (1/1) = 4 • Four terms = 4 * (1/1 - 1/3 + 1/5 - 1/7) = 2.8952380952 • Seven terms = 4 * (1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13) = 3.2837384837 Use a for statement that loops terms times to calculate the approximation. Each term divides one number by another: • The top number (numerator) is always 1. • The bottom number (denominator) is always an odd number. Use a variable for this that increments by two within each loop. Note from the formula that during an odd loop, we add the term to a running sum, and during an even loop, we subtract the term from a running sum. Use condition į %2=0 to determine whether a loop iteration is even or odd. Continue to use a validation loop to prompt for and get from the user the number of terms until they enter a sentinel value of 99. The overall structure of the program is: Define a constant for the numerator. Format all real numbers to ten decimal places. The output should look like this: Welcome to Fruity Fillers ------------------------- Enter the number of terms to approximate PI to (between 1 and 10,000, 99 to exit): 100000 Error: the number of terms must be between 1 and 10,000. Enter the number of terms to approximate PI to (between 1 and 10,000, 99 to exit): 500 PI to 500 term (s) is 3.1395926556. Enter the number of terms to approximate PI to (between 1 and 10,000, 99 to exit): 99 End of Fruity Fillers

User Athanor
by
4.2k points

1 Answer

5 votes

Step-by-step explanation:

Enter number of terms (1-10000): 1000

Estimated value: 3.14059

Enter number of terms (1-10000): 1

Estimated value: 4

Enter number of terms (1-10000): 10000

Estimated value: 3.14149

Enter number of terms (1-10000): 100000

Error!!

Code (modify count statements)

#include <bits/stdc++,h>

using namespace std;

#define Id long double

Id pi(int n){

Id sum=0:

int sign=1;

for(int i=0;i<n;i++){

Id num= sign*1.00/(2*i+1);

sign*=-1;

sum+=num;

}

return 4*sum;

}

int main(){

int n;

count<<"----Welcome----\\";

count<<"Enter number of terms(1-1000):";

cin>>n;

while(n!=99){

if(n>10000 or n<1)

count<<"Error!!\\";

else{

count<<"Estimated value;"<<pi(n)<<endl;

count<<endl<<endl;

}

count<<"Enter number of terms(1-10000):";

cin>>n;

}

}

User Bolaji
by
4.8k points