#include using namespace std; //generate and return a random number //from a to b: {a, a+1, ..., b-1, b} int random(int a, int b) { return rand() % (b - a +1) + a; } double computePI(int nT, int nH) { return 4 * ((double) nH / nT); } //return true if dart hits in circle of //radius r (centered at origin) //false otherwise bool throwOneDart(int r) { //Generate dart location int x = random(-1 * r, r); int y = random(-1*r, r); //Check if location is within circle if (sqrt(x * x + y * y) < r) return true; else return false; } //Return number of hits //from throwing n darts at //radius r board. int throwDartsCountHits(int r, int n) { int hits = 0; //throw n darts, increment hits on hit for (int i = 0; i < n; i++) { if (throwOneDart(r)) hits++; } return hits; } int main() { //variables int radius; int numThrows; int numHits; double PI; //Step 1: pick radius of board radius = 1000; //Step 2: pick number of throws numThrows = 800; //Step 3: throw the darts at the board, count hits numHits = throwDartsCountHits(radius,numThrows); //Step 4: compute PI from hits and throws PI = computePI(numThrows, numHits); //Step 5: report answer to user cout << "Our estimate for PI is : " << PI << endl; return 0; }