Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <ctime> // time
- #include <cstdlib> // rand, srand
- using namespace std;
- int six_sided_die[] = { 1, 2, 3, 4, 5, 6 }; // the die
- int tally_of_rolls[] = { 0, 0, 0, 0, 0, 0 }; // number of times each number is rolled
- // This function returns a randomly-generated number in the range of 1 - 6.
- int roll_die()
- {
- int random_number = 0; // random number from rand()
- int die_number = 0; // converted die number
- random_number = rand() % 6; // Generate a random number.
- die_number = six_sided_die[random_number]; // Convert to die number.
- return die_number; // Return the number generated.
- }
- // This function adds a die roll to the tally of rolls.
- void record_roll(int roll)
- {
- tally_of_rolls[roll - 1]++; // Add 1 to the specified die roll.
- }
- // This function displays a chart of how many of each number were rolled.
- void display_results()
- {
- cout << "\n\t\tSix-sided Die Rolled One Million Times\n\n"; // Display title for the chart
- cout << "Number\t" << "Was rolled this many times\n"; // DIsplay heading for the chart
- for (int i = 0; i < 6; ++i) // For each die roll,
- {
- cout << i + 1 << "\t" << tally_of_rolls[i] << "\n"; // Display how many times it was rolled.
- }
- cout << "\n"; // Go to the next line.
- }
- int main()
- {
- cout << "This program simulates " // Explain the program.
- "rolling a six-sided die one million times and\n"
- "counts how many times each number is rolled.\n"
- "It uses the rand() function, seeded with "
- "the current time.\n";
- cout << "\nPress enter when ready."; // Prompt for press enter.
- cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Wait for user to press enter.
- srand(time(NULL)); // Prepare the random number generator.
- int current_roll = 0; // This stores the current die roll.
- for (int x = 0; x < 1000000; ++x) // One million times,
- {
- current_roll = roll_die(); // Roll the die.
- record_roll(current_roll); // Record the result.
- }
- display_results(); // Display the results.
- return 0; // End the program.
- }
Add Comment
Please, Sign In to add comment