How can I use rand() to gen a number between two values?

Hi, can someone tell me how to use rand() to generate a random bumber between two values. I want to write a function "int get_rand(int low, int high);" that will return a random number inbetween (not including) the two ints that are passed to it.

Here is what I have of it so far:

1
2
3
int get_rand(int low, int high) {
    return ((rand() % high + 1) - low);
}


I'm getting other strange errors in my program so I haven't tested this function yet but I think it might work.
Nope, that doesn't work since you get values from 0...high. Minus 'low' means that you may get negative results. Plus 1 doesn't help.

So: ((rand() % (high - low)) + low). You may add 1 if you want
Here's a function I wrote for that:

1
2
3
4
5
6
7
8
9
int randomRange( int _Min, int _Max )
{
	//add 1 to the max, so it's included in the result.
	_Max += 1;

	int x = _Min + rand() % ( _Max - _Min );

	return x;
}
Lynx, I like that. I too have been looking for a simple way to do that. Thanks for sharing.
You're welcome. I never liked writing code for random numbers, because I kept forgetting it. So now I have a folder with functions I use all the time, lol.
I would love to raid that folder. . lmao
ahaha! I might put them on my site later, if I get time. Quite a lot of them are on there already:
http://sites.google.com/site/davevisone/
Nice :D Ok, I'll PM you so I don't hijack the OPs thread. :P

Sorry OP.
Thanks for the help, if only I was good enough at maths to have figured that out on my own. It seems so simple.
Topic archived. No new replies allowed.