1. ## Question about getting random number in range

Hi, I got the following line from the FAQ:

rc = (rand() % (max - min + 1) + min);

I know this does work but I'd rather know why my code is working. I'm not very mathmatically minded so if anyone could give me a bit of a walkthrough that'd be great.

Thanks

2. Try working it thru for some dice rolls. Good ol D&D nomenclature....

d6.....

rand() % ( 6-1+1) will give a number in range 0 to 5 adding 1 raises range to 1 to 6 i.e. d6

3d6

rand() % (18-3+1) will give you a number in range 0 to 15. adding 3 raises range to 3 to 18 or 3d6

starting to see how this works. When you understand the modulo operator everything else will fall into place.

3. Need to watch your () there Stoned_Coder

rand() % (6-1+1) would be the same as rand() % 6
rand() % (6-1) + 1 will give you the right results

4. err no thantos try again

5. Thanks it's clearer now

6. err yes Stoned_Coder

(6-1+1) is 6

(18-3+1) is 16

() are done before % which is done before +

7. Originally Posted by Stoned_Coder
err no thantos try again
i think you missed that he was making fun of you

8. srand(time());
number=rand()%<enter the number u want it to go up to here>;

make sure to #include<time.h>

9. err yes Stoned_Coder

(6-1+1) is 6

(18-3+1) is 16

() are done before % which is done before +
you were misusing the modulus operator.
Remember the first example I gave was for 1d6. My figures were correct. If you had thought about it you would have seen it.

6-1+1 is indeed 6. so rand()% 6 is what we are saying. This gives a random number in range 0 to 5 then we add min which in this case is 1 so range become 1 to 6.

You suggested for 1d6 that i want ....

rand() % (6-1) + 1

Lets look at this....

rand() % 5 gives us 0 to 4 then add 1 so 1 to 5. is that correct figures for 1d6 ?

so thantos looks like you were brainfarting after all

10. Ok so mine would have given 1 - 5, yours would have given 0 to 5. Both examples would have been wrong unless you purposly left off showing the + 1. Which is very easy for me to not see at 5:30 in the morning

But it really doesn't matter as using % for rand() is the lazy way that results in poor numbers.

11. quite right i was only showing this part of the eq....

rand() % (max-min+1)

Then i went on to describe adding min, didnt mathematically show it but even so you should have read my post properly and it is all explained.

12. Read? You mean I can't just look at the pretty dancing numbers?

13. Ok. here ya go, just for you....