68.2k views
2 votes
Approximation of PI: [50 marks] Write a C program that computes an approximation of pi (the mathematical constant used in many trigonometric and calculus applications) to four decimal places. A summation that can be used to compute pi is the following (from calculus).

User Nicolle
by
4.8k points

1 Answer

4 votes

Answer:

#include <iostream>

#include <cmath>

#include <iomanip>

using namespace std;

double piValue() {

double p = 1;

int i = 1;

while(true) {

double prev = p;

p += pow(-1, i) * (1.0 / (1 + 2*i));

if(abs(prev - p) < 0.00005) {

break;

}

i++;

}

return 4*p;

}

int main() {

cout << piValue() << endl;

}

**************************************************

User Thomas Lielacher
by
4.0k points