我正在尝试生成0到1之间的随机双数,但我总是0
func randFunct() -> Double {
let randomInt = arc4random_uniform(100) + 1 // [1, 100]
let randomDouble : Double = Double(randomInt/100)
return randomDouble
}
答案 0 :(得分:3)
试试这个:
extension Double {
private static let arc4randomMax = Double(UInt32.max)
static func random0to1() -> Double {
return Double(arc4random()) / arc4randomMax
}
}
print(Double.random0to1())
答案 1 :(得分:-1)
它解决了我的问题:
let randomDouble : Double = Double(arc4random()) / Double(UINT32_MAX) * abs(0 - 1) + min(0, 1)