tags:

views:

81

answers:

3

Possible Duplicate:
How to generate a random number from within a range - C

I'm looking for something I can use in C that will give me a random number between a and b. So something like rand(50) would give me a number between 1 and 50.

+3  A: 

From the comp.lang.c FAQ: How can I get random integers in a certain range?

jamesdlin
+1  A: 

You can use either rand or random to get an arbitrary random value, then you can take the result of that and mod it by the size of the range and then add the start offset to put it within the desired range. Ex:

(rand()%(b-a))+a
Michael Aaron Safyan
Be aware that unless (b-a) is a power of 2, you will NOT get a uniform distribution here. It will slightly favor the smaller values.
Tal Pressman
yes in fact even the man of rand suggests not to use rand()%N to get numbers from 0 to N-1, since the distribution gets skewed a bit. the proposed solution for num from 1 to 10 is `1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));`
ShinTakezou
A: 

You need to use rand() and srand().

http://linux.die.net/man/3/rand

Shelldon