You need to
seed the random the number generator.
A pseudo-random number generator, like
std::rand, gets random numbers by starting with a number and performing a bunch of operations on it to create the next number, in a way that you can't predict the results. However, if you start with the same number, you'll always end up getting the same numbers afterwards, too. Hence, seeding the random number generator so that it starts with a different number each time.
For
std::rand, the way to seed it is to use
std::srand, and some data that changes every time you run the program (like, say, the current time):
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
// use current time for seeding generator;
// only do this once in your program
std::srand(std::time(0));
std::cout << "Random number: " << (std::rand() % 999 + 1) << std::endl;
return 0;
}
|
Keep in mind that
std::rand is not a very good random number generator, particularly when using it in the way that you do. If you need numbers that are 'more random', try using the generators found in
<random>:
http://en.cppreference.com/w/cpp/numeric/random