How to select range of values when using arc4random()

后端 未结 6 475
北荒
北荒 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:28

    As pointed out in other posts below, it is better to use arc4random_uniform. (When this answer was originally written, arc4random_uniform was not available). Besides avoiding the modulo bias of arc4random() % x, it also avoids a seeding problem with arc4random when used recursively in short timeframes.

    arc4random_uniform(4)
    

    will generate 0, 1, 2 or 3. Thus you could use:

    arc4random_uniform(51)
    

    and merely add 50 to the result to get a range between 50 & 100 (inclusive).

提交回复
热议问题