0

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.

Community
  • 1
  • 1
Scott
  • 5,135
  • 12
  • 57
  • 74
  • Dupe http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range-c –  Jun 03 '10 at 08:02
  • @Neil: Those comments will be inserted automatically now, once you vote to close as a dupe. –  Jun 03 '10 at 10:56
  • @Roger I know - old habits die hard. –  Jun 03 '10 at 11:03

3 Answers3

3

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

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
1

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
  • 93,612
  • 16
  • 138
  • 200
  • 1
    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 Jun 03 '10 at 08:03
  • 1
    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 Jun 03 '10 at 08:37
0

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

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

Shelldon
  • 84
  • 4