随机双数字,在0和1之间的swift

时间:2016-08-26 17:55:49

标签: ios swift

我正在尝试生成0到1之间的随机双数,但我总是0

func randFunct() -> Double {
     let randomInt = arc4random_uniform(100) + 1 // [1, 100]
     let randomDouble : Double = Double(randomInt/100)
     return randomDouble
}

2 个答案:

答案 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)