简单来说,我该如何生成一个随机数呢?因为书中的方法每次都会选出相同的数字。
根据苹果发布的书籍,以下是在Swift中生成随机数的方法。
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
for _ in 1..10 {
// Generate "random" number from 1-10
println(Int(generator.random() * 10)+1)
}
问题在于我放在底部的那个for循环,输出结果看起来像这样:
4
8
7
8
6
2
6
4
1
每次运行,输出结果都相同,不管运行多少次。