Uploaded by alondra castro

Homework 1 (pi) schweller COmputer science

advertisement
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
//Ask user for radius of board, return that value
int getRadius()
{
cout << "Please enter the radius of the board: " << endl;
int r;
cin >> r;
return r;
}
//Ask user to enter number of darts to throw, return it.
int getThrows()
{
cout << "How many darts to throw?" << endl;
int t;
cin >> t;
return t;
}
//Throw one dart, return true if it hits,
//false if it misses.
bool throwADart(int r)
{
//Dart location
int x;
int y;
//Random numbers from -r to r.
x = rand() % (2 * r) - r;
y = rand() % (2 * r) - r;
//check if they hit
if (sqrt(x * x + y * y) < r)
return true;
else
return false;
}
//Throw 'throws' darts at board of given radius,
//and return total number of hits.
int shootTheDarts(int radius, int throws)
{
int hits = 0;
for (int i = 0; i < throws; i++)
{
if (throwADart(radius))
hits++;
}
return hits;
}
//Compute and return estimate for PI
//based on hits and throws
double computePI(int hits, int throws)
{
double answer = 4 * ((double) hits / throws);
return answer;
}
int main()
{
//step 0: declare variables
int radius;
int numThrows;
int numHits;
double PI;
//step 1: get radius of the board from user
radius = getRadius();
//step 2:
numThrows = getThrows();
//step 3:
numHits = shootTheDarts(radius, numThrows);
//step 4:
PI = computePI(numHits, numThrows);
//step 5: tell user the answer!
cout << "Your estimate for PI is : " << PI << endl;
return 0;
}
Download