Really quick rand() question

Started by
6 comments, last by rip-off 17 years, 1 month ago
Hey guys, Just trying to figure out if this is possible I'm trying to generate a random number between -30 and 30. How would I go about doing this. I know the code to get one for a number between 0 and 30:
int posX = (rand() % 30) + 1;
But what can I add to this line to make the beginning of the range -30? Many thanks
Advertisement
generate a number from 0 to 60 and subtract 30 from it.
int posX = rand()%61 - 30;
Your code generates a number in the range 0..30. Your new requirement is a range of 60, so you generate a number between 0..60. You can then offset the range by adding or subtracting a number from the range, moving the values in the range to

0 + N..60 + N.
Your code will get a number between 0 and 31. We take the remainder (modulus) when divided by 30. This is in the range 0 to 29 (between -1 and 30). We then add one and are in the range 1 to 30 (between 0 and 31).

To get between -30 and 30 (-29 to 29) we see that there is a total 59 different values so we get a in the range from 0 to 58 and subtract 29.

int posX = (rand()%59)-29;
Ah thanks guys, I did think of doing that, but thought there might be a way of setting up what the first number in the range is

But thats good enough for me, :)
If you want a way to simply set the low and high bounds, just do something like this:

int Random(int low, int high)
{
return low + rand()%(high-low+1);
}
Quote:Original post by Kuro
If you want a way to simply set the low and high bounds, just do something like this:

int Random(int low, int high)
{
return low + rand()%(high-low+1);
}


Ive heard that something like this is better ( something about the low order bits being less random than the higher order ones with rand() ):

return low + int(( rand() / float(RAND_MAX) ) * (high - low + 1) );

Hope I got the math right =/

This topic is closed to new replies.

Advertisement