Really quick rand() question

This topic is 4006 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

Share on other sites
generate a number from 0 to 60 and subtract 30 from it.

Share on other sites
int posX = rand()%61 - 30;

Share on other sites
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.

Share on other sites
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;

Share on other sites
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, :)

Share on other sites
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);
}

Share on other sites
Quote:
 Original post by KuroIf 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 =/