Site hosted by Angelfire.com: Build your free website today!
« February 2006 »
S M T W T F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28
Entries by Topic
All topics  «
Blog Tools
Edit your Blog
Build a Blog
RSS Feed
View Profile
Open Community
Post to this Blog
You are not logged in. Log in
C++ Programs from Random Places
Friday, 10 February 2006
Calculating Pi
//ThIS IS A NEAT PROGRAM THAT CALCULATES PI DEPENDING ON HOW MUCH
//ACCURACY YOU WANT
//**NOTE**: THIS MATERIAL IS NOT COPYRIGHTED AND IS OPEN FOR PUBLIC
//USE AND DISTRIBUTION

#include
#include "Dice.h"
using namespace std;

int main ()
//PURPOSE: use Monte Carlo Method to estimate pi
//PRECONDITIONS: none
//POSTCONDITIONS: displays the estimated value of pi
{
float totaldarts; // total number of darts to throw
float inside=0; // number of darts inside unit circle
float x,y; // coordinates of point where dart lands
float countdarts; // count darts thrown
float pi; // estimate for pi
Dice die(101); //create die with 101 sides

// prompt user for number of darts to throw
cout << "Enter number of darts to throw: ";
cin >> totaldarts;

// loop to throw and count darts
for(countdarts=0; countdarts<=totaldarts; countdarts++){
x=die.Roll();
y=die.Roll();
x=(x-1)/100;
y=(y-1)/100;
if(x*x + y*y <=1){
inside++;
}
}
// compute estimate of pi
pi=4.00*(inside/totaldarts);

// display estimate
cout << "The estimate of pi is: " << pi << endl;

return 0;
}

class Dice
{
public:
// constructor to create a die
Dice(int sides);
// return random roll of die
int Roll();
// how many sides this die has
int NumSides() const;
// number of times this die rolled
int NumRolls() const;

private:
// count # of times this die rolled
int myRollCount;
// save # of sides on this die
int mySides;
};


Posted by poetry/maddoxtheconqueror at 12:01 AM CST
Post Comment | Permalink | Share This Post

View Latest Entries