0

Possible Duplicates:
Generate Random numbers uniformly over entire range
In C, how do I get a specific range of numbers from rand()?

i want to generate random number in C. It has rand() and srand() function in stdlib.h But it gives me very large number. But I want only number b/w 1 to 10. So, is it possible and if yes then how? If is possible to generate character from a-z randomly.

Community
  • 1
  • 1
user12345
  • 2,400
  • 8
  • 33
  • 40
  • 1
    `rand() % 10 + 1` but watch out for bias – pmg Oct 06 '10 at 20:37
  • 2
    Many duplicates on SO already. e.g. http://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-entire-range, http://stackoverflow.com/questions/1202687/in-c-how-do-i-get-a-specific-range-of-numbers-from-rand – Paul R Oct 06 '10 at 20:38
  • vote to close... duplicate of [insert your favorite stack overflow C rand() question here] – Timothy Oct 06 '10 at 20:58

2 Answers2

8

The simplest way is to use the modulo operator to cut down the result to the range you want. Doing rand() % 10 will give you a number from 0 to 9, if you add 1 to it, i.e. 1 + (rand() % 10), you'll get a number from 1 to 10 (inclusive).

And before others complain, this may dilute the random distribution, nevertheless, it should work fine for simple purposes.

casablanca
  • 69,683
  • 7
  • 133
  • 150
1

Modulo (%) has some bias in it.

Slightly preferred is to scale the random number:

int aDigit = (int) (((double)rand() / (RAND_MAX+1)) * 9 + 1);
printf("%d", aDigit);

Breaking it down:

((double)rand() / RAND_MAX)

will generate a double between 0.0 and 0.99999

* 10

turns that to a number 0.0 to 9.9999.

+ 1;

turns that into 1.0 - 10.999

(int)

turns that into 1-10, which is what you asked for.

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • That approach has bias too. See: http://stackoverflow.com/questions/3746814/create-a-random-number-less-than-a-max-given-value/3746930#3746930 – jamesdlin Oct 07 '10 at 02:19