tags:

views:

123

answers:

2

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.

+6  A: 

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
Also don't forget to seed the random number generator or you'll get the same sequence each time on some systems.
Michael Shopsin
The OP already mentioned `srand` so I assume he knows about it.
casablanca
The modulo operator gives you an answer depending on the least significant bits, which in some RNGs are a lot less random than the most significant. I'd rather go with division.
David Thornley
A: 

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
That approach has bias too. See: http://stackoverflow.com/questions/3746814/create-a-random-number-less-than-a-max-given-value/3746930#3746930
jamesdlin