How to select range of values when using arc4random()

后端 未结 6 484
北荒
北荒 2020-12-04 20:02

Can I set a range of numbers when using arc4random()? For example 50-100 only.

6条回答
  •  误落风尘
    2020-12-04 20:12

    To expand upon JohnK comment.

    It is suggested that you use the following function to return a ranged random number:

    arc4random_uniform(51)
    

    which will return a random number in the range 0 to 50.

    Then you can add your lower bounds to this like:

    arc4random_uniform(51) + 50
    

    which will return a random number in the range 50 to 100.

    The reason we use arc4random_uniform(51) over arc4random() % 51 is to avoid the modulo bias. This is highlighted in the man page as follows:

    arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

    In short you get a more evenly distributed random number generated.

提交回复
热议问题