janac

Tally die rolls

Dec 20th, 2021 (edited)
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <ctime> // time
  4. #include <cstdlib> // rand, srand
  5. using namespace std;
  6.  
  7. int six_sided_die[] = { 1, 2, 3, 4, 5, 6 }; // the die
  8. int tally_of_rolls[] = { 0, 0, 0, 0, 0, 0 }; // number of times each number is rolled
  9.  
  10. // This function returns a randomly-generated number in the range of 1 - 6.
  11. int roll_die()
  12. {
  13.     int random_number = 0; // random number from rand()
  14.     int die_number = 0; // converted die number
  15.     random_number = rand() % 6; // Generate a random number.
  16.     die_number = six_sided_die[random_number]; // Convert to die number.
  17.     return die_number; // Return the number generated.
  18. }
  19.  
  20. // This function adds a die roll to the tally of rolls.
  21. void record_roll(int roll)
  22. {
  23.     tally_of_rolls[roll - 1]++; // Add 1 to the specified die roll.
  24. }
  25.  
  26. // This function displays a chart of how many of each number were rolled.
  27. void display_results()
  28. {
  29.     cout << "\n\t\tSix-sided Die Rolled One Million Times\n\n"; // Display title for the chart
  30.     cout << "Number\t" << "Was rolled this many times\n"; // DIsplay heading for the chart
  31.     for (int i = 0; i < 6; ++i) // For each die roll,
  32.     {
  33.         cout << i + 1 << "\t" << tally_of_rolls[i] << "\n"; // Display how many times it was rolled.
  34.     }
  35.     cout << "\n"; // Go to the next line.
  36. }
  37.  
  38.  
  39. int main()
  40. {
  41.     cout << "This program simulates " // Explain the program.
  42.         "rolling a six-sided die one million times and\n"
  43.         "counts how many times each number is rolled.\n"
  44.         "It uses the rand() function, seeded with "
  45.         "the current time.\n";
  46.  
  47.     cout << "\nPress enter when ready."; // Prompt for press enter.
  48.     cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Wait for user to press enter.
  49.  
  50.     srand(time(NULL)); // Prepare the random number generator.
  51.     int current_roll = 0; // This stores the current die roll.
  52.  
  53.     for (int x = 0; x < 1000000; ++x) // One million times,
  54.     {
  55.         current_roll = roll_die(); // Roll the die.
  56.         record_roll(current_roll); // Record the result.
  57.     }
  58.     display_results(); // Display the results.
  59.  
  60.     return 0; // End the program.
  61. }
  62.  
Add Comment
Please, Sign In to add comment