Generating random integer from a range

前端 未结 13 1649
失恋的感觉
失恋的感觉 2020-11-22 03:12

I need a function which would generate a random integer in given range (including border values). I don\'t unreasonable quality/randomness requirements, I have four requirem

13条回答
  •  无人共我
    2020-11-22 03:53

    Here is an unbiased version that generates numbers in [low, high]:

    int r;
    do {
      r = rand();
    } while (r < ((unsigned int)(RAND_MAX) + 1) % (high + 1 - low));
    return r % (high + 1 - low) + low;
    

    If your range is reasonably small, there is no reason to cache the right-hand side of the comparison in the do loop.

提交回复
热议问题