Write a C++ program in a file named pi.cpp that approximates the value of the constant π. Once again you should not resort to using predefind constants and functions for π, that are provided by C++ standard libraries. Instead you should compute the value of π based on the Leibniz formula for π.

Respuesta :

Answer:

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.    int t = 2;
  6.    int divisor = 3;
  7.    float l_series=1;
  8.    bool flag = true;
  9.    
  10.    while(t <= 10000){
  11.        if(flag){
  12.            l_series = l_series - (1/(float)(divisor));
  13.            flag = false;
  14.          
  15.        }else{
  16.            l_series = l_series + (1/(float)(divisor));
  17.            flag = true;
  18.        }
  19.        t++;
  20.        divisor+=2;
  21.    }
  22.    cout<<"PI value: "<< l_series * 4;
  23. }

Explanation:

Firstly, we declare several variables t, divisor, l_series and flag. The variable t denotes the current term. We start the term with 2. We can write the Leibniz formula in form of this expression

l_series - (1/(float)(divisor))

or

l_series + (1/(float)(divisor))

We put the expression in a while loop and put a flag in an if statement. If the flag is true, run the expression l_series - (1/(float)(divisor)) and then set the flag to false (Line 12 -14).

If the flag is false run the expression   l_series = l_series + (1/(float)(divisor)) and then set the flag to true.

Next increment the term by one and divisor by two before proceeding to the next term of calculation.

At the end, print the approximated PI value by multiplying l_series by 4. If we count for 10000 terms, we shall get the PI value 3.1415