just wondering, if I have the following code:
int randomNum = rand() % 18 + (-9);
will this create a random number from -9 to 9?
You are right in that there are 18 counting numbers between -9 and 9 (inclusive).
But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.
Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.
Also, manpage for the rand function quotes:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
So in your case this would be:
int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));
Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.
Pseudo-code:
std::mt19937 gen(someSeed);
std::uniform_int_distribution<int> dis(-9, 9);
int myNumber = dis(gen)
Your code returns number between (0-9 and 17-9) = (-9 and 8).
For your information
rand() % N;
returns number between 0 and N-1 :)
The right code is
rand() % 19 + (-9);
Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.
No, it won't. You're looking for:
int randomNum = rand() % 19 + (-9);
There are 19 distinct integers between -9 and +9 (including both), but rand() % 18
only gives 18 possibilities. This is why you need to use rand() % 19
.