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, don't forget to seed your PRNG once and only once:
srand(time(NULL));
Then, this function should do what you want.
(lightly tested, seems to work)
int RandRange(int Min, int Max)
{
int diff = Max-Min;
return (int) (((double)(diff+1)/RAND_MAX) * rand() + Min);
}
In your case, you'll want to:
x = RandRange(100, 800); /* x will be between 100 and 800, inclusive */
This uses floating-point math, which may be slower than modulo (%) arithmetic, but will have less bias.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With