#include #include #include #include // returns a randomly chosen number between 1 and 6 int roll_die () { double x; x = rand() / (RAND_MAX + 1.0); // x is now random: 0 <= x < 1 return 1 + ((int) (x * 6)); } int roll_bad_die () { double x; x = rand() / (RAND_MAX + 1.0); // x is now random: 0 <= x < 1 if (x < 0.16) return 1; if (x < 0.32) return 2; if (x < 0.52) return 3; if (x < 0.68) return 4; if (x < 0.84) return 5; return 6; } // simulates one game of Craps // returns true if the player wins ("made the pass") and false otherwise // sets "number_of_rolls" to the number of rolls required to produce an outcome // set "firsat_roll_was_a_12" to true or false depending upon whether the first // roll produced this total bool player_made_pass (int &number_of_rolls, bool &first_roll_was_a_12) { int total, point; // simulate first roll total = roll_die() + roll_bad_die(); // note: 2 * roll_die() would be WRONG!! number_of_rolls = 1; // assigns a boolean value to a boolean variable... first_roll_was_a_12 = (total == 12); // see if player has scored a "natural" if ((total == 7) || (total == 11)) { return true; } // see if the player has "crapped out" if ((total == 2) || (total == 3) || (total == 12)) { return false; } // a "point" has been established point = total; // keep rolling until we repeat the point or a 7 is rolled for (;;) { total = roll_die() + roll_bad_die(); // note: 2 * roll_die() would be WRONG!! number_of_rolls++; if (total == 7) { return false; } if (total == point) { return true; } } } int main (void) { long i, pass_wins, dont_pass_wins, dont_pass_ties, total_rolls, count; int rolls; bool first_roll_was_a_12; for (;;) { cout << endl << "Enter number of games to be simulated (0 to stop): "; cin >> count; if (count <= 0) { return 0; } pass_wins = dont_pass_wins =dont_pass_ties = total_rolls = 0; for (i = 0; i < count; i++) { if (player_made_pass (rolls, first_roll_was_a_12)) { pass_wins++; } else { if (first_roll_was_a_12) { dont_pass_ties++; } else { dont_pass_wins++; } } total_rolls += rolls; } cout << endl << "A game of craps lasts an average of " << double(total_rolls) / count << " rolls." << endl; cout << "A pass bet wins " << (100.0 * pass_wins) / count << "% of the time." << endl; if (dont_pass_ties != count) { // play safe - avoid division by zero cout << "Ignoring ties, a don't pass bar 12 bet wins " << (100.0 * dont_pass_wins) / (count - dont_pass_ties) << "% of the time." << endl; } else { cout << "The don't pass bar 12 bet ties 100% of the time." << endl; } } // end for (;;) }