1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <cstdlib> // For srand() and rand() #include <ctime> // For time() using namespace std; int main() { // Initialize random seed based on current time srand(static_cast<unsigned int>(time(0))); // Generate a random number between 1 and 100 int randomNumber = rand() % 100 + 1; cout << "Random Number Generated: " << randomNumber << endl; return 0; } |
Explanation
- Include Necessary Headers:
#include <cstdlib>
: This header provides functions likesrand()
for seeding the random number generator andrand()
for generating random numbers.#include <ctime>
: This header is used to get the current time, which is used as a seed to ensure the random numbers are different each time the program runs.
- Seeding the Random Number Generator:
srand(static_cast<unsigned int>(time(0)));
: This line seeds the random number generator with the current time. Thetime(0)
function returns the current time as the number of seconds since January 1, 1970, which ensures that the seed is different every time the program is run. Thestatic_cast<unsigned int>
ensures the correct type for thesrand()
function.
- Generating a Random Number:
int randomNumber = rand() % 100 + 1;
: This line generates a random number between 1 and 100. Therand()
function returns a random integer, and the% 100
operation limits the range to 0-99. Adding1
shifts this range to 1-100.
- Outputting the Random Number:
cout << "Random Number Generated: " << randomNumber << endl;
: This line simply outputs the generated random number to the console.