我在使用arc4random()函数时,能否设置一个数字范围?比如只生成50到100之间的随机数。
我在使用arc4random()函数时,能否设置一个数字范围?比如只生成50到100之间的随机数。
正如以下其他帖子所指出的那样,最好使用arc4random_uniform
。(当撰写此答案时,arc4random_uniform
尚不可用)。除了避免arc4random() % x
的模数偏差之外,它还避免了在短时间内递归使用arc4random
时出现的种子问题。
arc4random_uniform(4)
将生成0、1、2或3。 因此,您可以使用:
arc4random_uniform(51)
只需将结果加50即可得到50至100(包括100)之间的范围。
为了进一步解释JohnK的评论。
建议您使用以下函数返回范围内的随机数:
arc4random_uniform(51)
这个函数会返回一个在 0
到 50
范围内的随机数。
然后你可以添加你所需要的下限值,例如:
arc4random_uniform(51) + 50
该函数将返回在范围 50
到 100
内的随机数。
我们使用 arc4random_uniform(51)
而不是 arc4random() % 51
是为了避免出现模数偏差。这在文档中有如下说明:
arc4random_uniform(upper_bound) 将返回一个小于 upper_bound 的均匀分布的随机数。与“arc4random() % upper_bound”等构造相比,建议使用 arc4random_uniform(),因为它在上限不是2的幂时可以避免“模数偏差”。
简而言之,您可以生成更均匀分布的随机数。
int fromNumber = 10;
int toNumber = 30;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
将生成10
和30
之间的随机数,例如11,12,13,14......29
//range from 50 to 100
int num1 = (arc4random() % 50) + 50; or
int num1 = arc4random_uniform(50) + 50;
//range from 0-100
int num1 = arc4random() % 100; or
int num1 = arc4random_uniform(100);
func generateRandomKey(fromRange rangeFrom:Int, toRange rangeTo:Int) -> Int{
let theKey = arc4random_uniform(UInt32(rangeTo - rangeFrom)) + UInt32(rangeFrom)
return Int(theKey)
}
将始终为您提供随机范围整数。
int fromNumber = 10;
int toNumber = 30;
toNumber ++;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;