1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { // Initialize random seed srand(static_cast<unsigned>(time(0))); // Simulate rolling a dice int roll = rand() % 6 + 1; // Random number between 1 and 6 // Output result cout << "You rolled a: " << roll << endl; return 0; } |
Explanation
- Headers:
<iostream>
: For input and output operations.<cstdlib>
: For therand()
andsrand()
Advertisement<ctime>
: For thetime()
function to seed the random number generator.
- Main Function:
- Initialize Random Seed:
srand(static_cast<unsigned>(time(0)));
: Seeds the random number generator with the current time. This ensures different sequences of random numbers each time the program is run.
Advertisement - Simulate Rolling a Dice:
int roll = rand() % 6 + 1;
: Generates a random number between 1 and 6.rand() % 6
generates a number from 0 to 5, and adding 1 shifts this range to 1 to 6.
- Output Result:
- Prints the result of the dice roll to the console.
- Initialize Random Seed:
Notes:
- Randomness: The
rand()
Advertisementtime(0)
ensures that the numbers are different each time the program is executed. - Range Calculation: The expression
rand() % 6
provides a value between 0 and 5. Adding 1 adjusts this range to 1 through 6, which matches the typical outcome of rolling a six-sided dice.