Picking random number between two points in C

走远了吗. 提交于 2020-01-14 10:34:06

问题


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.



来源:https://stackoverflow.com/questions/9571738/picking-random-number-between-two-points-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!