20-CS-122-001 Computer Science II Spring 2012
Calculate the digits of π

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev     Next     Lectures     pi.cc     pi2.cc     pi2a.cc     pi3.cc

```#include <iostream>
#include "bigint.h"
#include "rational.h"
using namespace std;

// From the continued fraction
//  4/pi  =            1
//           1 + --------------
//                         4
//                3 + --------------
//                             9
//                     5 + -----------
//                                 16
//                          7 + ----------
//                                     25
//                               9 + ---------
//                                          36
//                                    11 + -------
//                                               49
//                                          13 + ----
//                                               ...
int main (int argc, char **argv) {
if (argc != 2) {
cout << "Calculate digits of pi\n";
cout << "Usage: " << argv[0] << " <number-of-iterations>\n";
exit(0);
}

int n = atoi(argv[1]);
Rational *frac = new Rational(0);
Rational *four = new Rational(4);
for (int i=n-1 ; i >= 0 ; i--) {
printf("\r%d    ",n-i); fflush(stdout);
Rational *r1 = new Rational(2*i+3);
Rational *r2 = new Rational((i+1)*(i+1));