A simple way to generate a random number in C++ is by using the rand()
method.
Here's an application that prints out 10 random numbers from a user specified range:
int randomNumber(const int min, const int max) {
const int range = max - min + 1;
return rand() % range + min;
}
int main() {
// Seed the random number generator with the current time.
// Without this the random numbers will always be the same.
srand(time(0));
int min, max;
std::cout << "Lower bound: ";
std::cin >> min;
std::cout << "Upper bound: ";
std::cin >> max;
std::cout << "Ten numbers between " << min << " and " << max << ":\n";
for(int i = 0; i < 10; i++) {
std::cout << randomNumber(min, max) << "\n";
}
}
Note: The rand()
method when combined with a modulus is slightly biased towards smaller numbers, but it will do for our use case.
Thanks @edurla. Fix.