| I have one thing to say first of all: the rand() function is not a member of the std namespace. It is a C function, so it is not technically a member of any named namespace. I've seen some code do things such as using ::printf; to use the printf() function, but as far as I know, it isn't actually necessary.
Here is the algorithm that you are using:
min_value + rand() % (max_value - min_value + 1)
That is, min_value would be 1 and max_value would be 6. To see the math behind it:
1 + rand() % (6 - 1 + 1)
The reason why you use modulo 6 is because rand() returns a value between 0 and the constant RAND_MAX (RAND_MAX is a constant defined in stdlib.h (cstdlib in C++), and the minimum value for RAND_MAX is supposed to be 32767). Obviously, you don't want to test the entire range of possible random numbers, just a limited range. That is why modulus is there.
In case you don't know, modulo 6 refers to the remainder in C++. That means that if you have 6 / 6 = 1, there is no remainder. However, if you do 5 / 6 = 0, the remainder is 5. Likewise, 1234 / 6 = 205 with a remainder of 4. In other words, 5 % 6 = 5 and 1234 % 6 = 4. Modulo operations return a value in the range of 0 to (second_operand - 1), where 6 would be the second_operand in the above example. That means that it would render a value in the range of 0 to 5 inclusive. Adding 1 to the result of that makes the range 1 to 6. I'm assuming that it is a dice rolling program since traditional dice have 6 sides.
Also, if that generates different values for you, I'm shocked since the random number generator hasn't even been seeded using the srand() function, which is also found in the same header as rand() and RAND_MAX.
Edit: As for how it works, I have no clue about the internals, especially since the implementation is compiler-specific. The general idea is that a value is selected from an internal table of numbers using a complex algorithm that operates on the seed value.
Last edited by rpgfan3233 : 07-26-2007 at 11:41 PM.
Reason: Had to answer the last question about how rand() works.
|