|
Pub Walk Simulation Program
#include <iostream>
using namespace std;
#include <ctime>
#include <cstdlib>
#include <iomanip>
void walk(int, int, float, float&, float&); // prototype
int main()
{
int start, walks;
float pub_prob, at_pub, avg_blks;
cout << "Enter probability of going towards the
pub: ";
cin >> pub_prob;
cout << "Enter number of walks: ";
cin >> walks;
cout << "Enter number of the starting block (2
- 7): ";
cin >> start;
srand( time(NULL)); // seed
// call function walk
walk(start, walks, pub_prob, at_pub, avg_blks);
// display results
cout << setiosflags(ios::fixed) << setprecision(2);
cout << "Starting at block " << start
<< "\nSafe at
home " << (100. - at_pub) << " per cent of walks"
<< "\nBack at
pub " << at_pub << " per cent of walks"
<< "\nAverage
number of blocks walked " << avg_blks
<< endl <<
endl;
}
void walk(int start, int walks, float p, float& at_pub, float&
avg_blks)
{
int i, block, pub = 0, num_blks = 0;
float rannum;
for (i = 1; i <= walks; i++)
{
block = start; // initialize block
while(block > 1 && block
< 8)
{
rannum =
static_cast< float >( rand() ) / RAND_MAX; // get random #
num_blks++;
// increment number of blocks walked
if ( rannum
< p )
block = block - 1; // move toward pub
else
block = block + 1; // move toward home
// cout <<
"random = " << rannum << " block = " << block
<< endl;
} // end while loop
if (block == 1)
pub++; // at the
pub
} // end for loop
// calculate statistics
at_pub = 100. * static_cast< float >( pub ) / walks;
avg_blks = static_cast< float >( num_blks) / walks;
}
% g++ walk2.cpp
% a.out
Enter probability of going towards the pub: .666
Enter number of walks: 500
Enter number of the starting block (2 - 7): 4
Starting at block 4
Safe at home 5.00 per cent of walks
Back at pub 95.00 per cent of walks
|