我试图种子斯威夫特使用srand(time(NULL))
随机数生成器,但我得到这个编译器错误:使用函数srand(时间(NULL))在斯威夫特会产生编译错误
Use of unresolved identifier 'NULL'
有另一种方式我应该使用srand()?
我试图种子斯威夫特使用srand(time(NULL))
随机数生成器,但我得到这个编译器错误:使用函数srand(时间(NULL))在斯威夫特会产生编译错误
Use of unresolved identifier 'NULL'
有另一种方式我应该使用srand()?
对于某些编译器,这个NULL==0
是不正确的。我们使用NULL
作为指针。试试这个:
srand(time(0));
雨燕采用nil
为NULL指针,以及time()
返回值必须 被强制转换为UInt32
:
srand(UInt32(time(nil)))
但考虑使用arc4random()
或其变体,而不是。从http://nshipster.com/random/:
arc4random
does not require an initial seed (withsrand
orsrandom
), making it that much easier to use.arc4random
has a range up to 0x100000000 (4294967296), whereasrand
andrandom
top out at RAND_MAX = 0x7fffffff (2147483647).rand
has often been implemented in a way that regularly cycles low bits, making it more predictable.
例如,
let x = arc4random_uniform(10)
产生范围为0的随机数... 9.
感谢,马丁河你是对的arc4random()可能是一个更好的选择。但我很高兴你为我清除了srand()。 – user3011204 2014-09-01 18:06:18
这个答案应该被接受。 – sudo 2015-07-27 21:25:36
我用函数srand(时间(0)),并尝试获取一个不同的错误: – user3011204 2014-09-01 17:58:16
错误是'time_t'不能转换为'UInt32' – user3011204 2014-09-01 17:59:08