我正在尝试使用 srand(time(NULL))
在 Swift 中为随机数生成器播种,但出现此编译器错误:
Use of unresolved identifier 'NULL'
还有其他方法可以使用 srand() 吗?
最佳答案
Swift 使用 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 范围内的随机数。
关于swift - 在 Swift 中使用 srand(time(NULL)) 会产生编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25610857/