I want to start by saying you should probably be using C++11 random functions rather than srand/rand. srand/rand are kind of crappy.
But that aside:
But why do I need these libraries |
srand() exists inside the cstdlib header. Without it, the compiler has no idea what you're trying to do when you call it.
time() exists inside the ctime header. Ditto.
why do I need to call this function? How does it works? |
Pseudo-random number generators are basically mathematical equations. You can think of it like this:
- They take an input number X
- They run that number through a crazy math formula to produce another number Y
- Y is your generated random number
- Y is then used as the next 'X' the next time you are to generate a number.
So each time you call rand() to get a new number, the generator has new input, which means you get new output.
What srand does... is it "seeds" the RNG -- IE: it gives it a starting point (that initial input). Without seeding, I believe srand starts with a seed of 0. So you'll still get random numbers from rand(), but they will be the same sequence of numbers each time you run the program because they have the same starting point.
By giving time() to srand(), you are seeding the RNG with the current time. Since the current time changes every second, this means that each time the user starts the program, the time is different, and therefore the RNG is seeded with a different number, and therefore you'll get a different sequence each time.
Also, what's the right way to set ranges? |
With rand(), the best practical way is to just use the mod operator (%).
Mod gives you the remainder after a division. So... 7%3 would be 1, because 7/3 is 2
remainder 1.
This is useful because any number divided by X is going to have a remainder that falls between [0,X). IE,
foo % 3
is going to be either 0,1, or 2... regardless of what 'foo' is.
So with rand(), this effectively creates a range:
1 2 3 4 5 6 7 8 9 10
|
int x = rand() % 5; // x will be 0,1,2,3, or 4
// From there, if you want to adjust where the range starts, you can just offset it by adding:
x += 2; // 0,1,2,3,4 now becomes 2,3,4,5,6
// So if you want a random number between [5,12) ... you could do this:
x = (rand()%7) + 5;
// %7 gives you [0,7)
// +5 gives you [5,12)
| |