Sign in to follow this  
Steedie

Really quick rand() question

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
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 =/

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this