// RandDemo.cc // features: // * uses random() to get a random integer // * gets parameters from command line // * uses "if" #include #include using namespace std; #define ranf() \ ((double)random()/(1.0+(double)RAND_MAX)) // Uniform from interval [0,1) */ int main(int argc, char* argv[]) { int outcome, N=10, count_in=0 ; long seed=123 ; double fraction_in ; if(argc>1) { sscanf( argv[1], "%d", &N ) ; // put the first command-line argument in N } if(argc>2) { sscanf( argv[2], "%ld", &seed ) ; // put the 2nd argument in seed } // Write out a summary of what's going to happen cout << "# " << argv[0] << " N=" << N << " seed=" << seed << endl ; // Initialise random number generator srandom(seed); // Perform N experiments. for(int n=1; n<=N; n++) { double x = ranf(); double y = ranf(); if ( x*x + y*y < 1.0 ) { outcome = 1 ; count_in++ ; } else { outcome = 0 ; } //Integer variables must be converted (cast) for correct division fraction_in = static_cast(count_in)/n; cout << "Location" << outcome << "\t" << x << "\t" << y << "\t" << count_in << "\t" << n << "\t" << 4.0 * fraction_in << endl; } return 0; }