问题描述
希望找到如何格式化 arc4Random()
的调用,以使用从-10到10的数字范围。
Looking to find how I would format a call to arc4Random()
to use a range of numbers from -10 to 10.
还是 arc4Random()
仅生成从0到X的内容?如果是这种情况,我将需要处理 arc4Random()
的结果,以便可能是指定范围内的结果?
Or does arc4Random()
only generate from 0 to X? If that's the case I will need to manipulate the result from arc4Random()
so that it may be a result within the specified range?
推荐答案
arc4random
返回 u_int32_t
,这是未签名的类型。您需要将其转换为带符号的类型,然后减去。
arc4random
returns a u_int32_t
, which is an unsigned type. You need to cast it to a signed type and then subtract.
我假设您希望数字介于-10到+10之间(包括-10和+10)
I assume you want a number from -10 to +10 inclusive (you want both -10 and +10 to be chosen sometimes).
如果定位的是iOS 4.3或更高版本,或者Mac OS X 10.7或更高版本,则应使用 arc4random_uniform
函数:
If you are targetting iOS 4.3 or later, or Mac OS X 10.7 or later, you should use the arc4random_uniform
function:
int myNumber = (int)arc4random_uniform(21) - 10;
如果要定位较旧的操作系统,则必须使用 arc4random
:
If you are targetting an older OS, you have to use arc4random
:
int myNumber = (int)(arc4random() % 21) - 10;
这篇关于arc4random()范围包括负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!