7.5k views
0 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:

1 Answer

7 votes

Answer:

The program to this question can be described as follows:

Program:

#include<iostream> //defining header file

#include<iomanip>

using namespace std;

int main() //defining main method

{

int n,i,div = 1; //defining integer variable

double PI = 0; //defining double variable

cout<< "Enter number of terms: "; //print message

cin >>n;//input number

while(n<1)//loop for input validation

{

cout << "Enter valid number of terms(atleast 1): "; //print message

cin >> n; //input value

}

for(i = 1; i <= n; i++) //loop to calcluate value

{

if(i % 2 == 0)//to check even number

PI =PI- (1.0/(div)); //hold value in PI

else//Odd iteration

PI =PI+ (1.0/(div)); //hold value in PI

div =div+ 2; //increment the value

}

PI =PI* 4;//Multiply summed values by 4

cout << "Approximation of PI = " << setprecision(10) << fixed << showpoint << PI; //print the value

return 0;

}

Output:

Enter number of terms: 8

Approximation of PI = 3.0170718171

Step-by-step explanation:

In the above program code three integer variable "i,n and div", in which variable div assign a value that is 1, and a double variable PI is defined, that assign a value that is 0.

  • The variable n is used to take input from the user end, that first checks input validation by using a while loop, and then the for loop is declared.
  • Inside the for loop, it will use if statement, that checks even or odd number, in the even number it decrements the value PI, and in the odd number, it will calculate the total PI.
User Debasmita Sarkar
by
5.3k points