我試圖種子斯威夫特使用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