CODE:
file: Pi.h
class Pi {
public:
Pi(const int nTerms);
double apprErr();
void print();
private:
int n;
double value();
};
file: Pi.cpp (I've written the main function in this file)
#include<iostream>
#include <cmath>
#include "Pi.h"
using namespace std;
Pi::Pi(const int nTerms) {
n = nTerms;
}
double Pi::apprErr() {
return abs(M_PI - value());
}
void Pi::print() {
cout << "Pi with "<< n << " terms: ";
cout << value();
cout << endl;
}
double Pi::value() {
double pi = 0.0;
int divisor = 1;
for(int i =1; i <= n; i++) {
if (i%2 == 1) {
pi += (4/(double)divisor);
} else {
pi -= (4/(double)divisor);
}
divisor += 2;
}
return pi;
}
int main() {
Pi pi1(3);
pi1.print();
cout << pi1.apprErr();
return 0;
}
Sample output:
Pi with 3 terms: 3.46667
0.325074
* Go through the code and try executing them, you'll understand them.
* Hope my response got you what you're looking for (If it did, please do Upvote!). If you have any doubt while grasping the code, feel free to ask.
Happy coding. :)