Picking random number between two points in C

2019-06-25 06:52发布

问题:

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

回答1:

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.



回答2:

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.

int rand_between(int l, int r) {
  return (int)( (rand() / (RAND_MAX * 1.0f)) * (r - l) + l);
}


回答3:

Look at the modulus operator.

int r = rand();
r = (r % 700) + 100;

700 is the difference of the range.



标签: c random