Hello I was wondering if anyone could help me with this programming assignment i
ID: 3782827 • Letter: H
Question
Hello I was wondering if anyone could help me with this programming assignment in C++. Thanks in advance! : Pi, a mathematical constant commonly approximated as 3.14159, is the ratio of a circle's circumference to its diameter. It is usually represented by the Greek letter . Write a C++ program that approximates the value of pi using the Gregory-Leibniz formula. Since this formula is an infinite series, you will need to prompt the user for the number of iterations (summation terms) they want to use in the calculation. For example, if the user indicates "4" iterations, the result would be = 4 - 4/3 + 4/5 - 4/7 or approximately 2.89524. If the user indicates "10" iterations, the result would be = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 + 4/17 - 4/19 or approximately 3.04184. If the user indicated "10000" iterations, the result would be approximately 3.14149. Thus, as the number of summation terms increases, the result converges on true value of PI. Rather than putting all your code in main(), use functions to perform the calculation. Embed your program in a loop so that the calculation can be repeated multiple times.
Explanation / Answer
#include <iostream>
using namespace std;
//function declaration
float gl_formula(int iter);
int main() {
// variables for iteration numbers and result
int input=10;
float result=0;
//getting input for number of iterations
cout <<" Please enter the number of iteration for using Gregory-Leibniz formula :";
cin >> input ;
//using the function to calculate pi using GL formula
result=gl_formula(input);
//displaying result
cout <<" Approximate value of pi using the Gregory-Leibniz formula is ("<<input <<" iterations)" <<result;
return 0;
}
//function to calculate pi using GL formula
float gl_formula(int iter)
{
//initial variables
float nu_const=4;
float de_var=1;
float pi=0;
for (int i = 1; i <= iter; i++) {
//check whether to add or subtract on this iteration
if(i%2==1)
{ pi=pi+(nu_const/de_var); }
else
{ pi=pi-(nu_const/de_var); }
//increasing denominator for next iteration
de_var=de_var+2;
}
return pi;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.