This is probably a stupid question, but I’m really struggling with this concept. I’m going through a tutorial explaining about arrays and the rand() function. I have two problems.
The first is, obviously to simulate one dice we need to randomly generate a number from 1-6. The book suggests this:
int RollOne( void ) {
return (rand() % 6) + 1;
}
Right, well rand() can generate any number from 0-32767. We then find the remainder of this number when it’s divided by 6, then add 1. E.g. 3245 is randomly generated. We divide it by 6, giving 540.8333 and take the remainder. 8.333 (truncated to 8 I believe) and then add 1. Unless I’m going mad, that makes 9, which is not between 1-6. The program runs fine however and I just can’t understand how we get a number from 1-6 using that code! Any help would be greatly appreciated.
The second problem I have isn’t really as major, but is relevant. The book left out what this bit of code means:
srand( clock() );
All that is mentioned is that srand() initialises a random number generator using the seed provided by clock(). Right, now can we actually input anything into clock(), if so what is its effect? Just a little explanation of what srand( clock() ) does would be perfect.
Sorry for the long post, I hope you don’t mind the wall’o’text. Any help would be really appreciated.
Thanks,
Mike
ANSWERED
Thank you everyone: I realise what I was doing. As shown by you guys, the % operator doesn’t divide, it just finds the difference between the highest multiple and the operand. Got it! I was under the impression that the remainder meant the decimal. I.e. If 7/2 = 3.5 then the remainder is 0.5. Now that I’ve written it out, I see how stupid I’ve been. Glad my A-level maths counts for something…..
Thanks again!
You are confused between integer truncation and remainders. When you divide 3245 by 6 using integer math the remainder is 5 (or 0.83333 * 6 = 5).
Another way to see this is 540 * 6 = 3240, which leaves a remainder of 5.