I was wondering, is it possible to generate a random number between two limits in c. I.e. my program is set like this:
function x
{
generate random number;
}
while(1)
{
function x;
delay
}
so bascially I want a random number to be generated everytime the function is called , but the number has to be between, for example, 100 and 800
I know there is a already made function called random and randmize in stdlib.h
I just dont know how to create the upper and lower limits
Thank you
First get a random number between 0 and 1 (
R
). Then scale this to the desired range (R* (right limit - left limit)
). Then add the min desired value.First, don't forget to seed your PRNG once and only once:
Then, this function should do what you want.
(lightly tested, seems to work)
In your case, you'll want to:
This uses floating-point math, which may be slower than modulo (%) arithmetic, but will have less bias.
Look at the modulus operator.
700 is the difference of the range.