How to generate a random integer number from within a range

后端 未结 11 1230
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 23:57

This is a follow on from a previously posted question:

How to generate a random number in C?

I wish to be able to generate a random number from within a part

11条回答
  •  你的背包
    2020-11-22 00:44

    In order to avoid the modulo bias (suggested in other answers) you can always use:

    arc4random_uniform(MAX-MIN)+MIN
    

    Where "MAX" is the upper bound and "MIN" is lower bound. For example, for numbers between 10 and 20:

    arc4random_uniform(20-10)+10
    
    arc4random_uniform(10)+10
    

    Simple solution and better than using "rand() % N".

提交回复
热议问题