使用 arc4random_uniform 到 return 一个完整的和非完整的双打

Using arc4random_uniform to return a both whole and non whole doubles

使用 Swift,我想弄清楚如何使用 arc4random_uniform 到 return 像 37.7 这样的数字。我必须遵守的指导是我必须在函数中执行,随机双倍必须在 0 - 300 之间。我已经能够构建一个函数,在范围内随机 returns 双倍但找不到任何会导致我输出随机非整数的东西

//function to randomly generate a double number like 105.3
func makeRandDbl() -> Double {
    let randGenerator: Double = Double(arc4random_uniform(301))
    print(randGenerator)

return randGenerator
}

makeRandDb()

一种方法是将 arc4random_uniform 的结果转换为 double,将结果除以 UInt32.max,然后将结果乘以 300。

let rand = 300 * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)

这将产生 0 到 300 之间的值,包括端值。您将获得的可能值的数量是 UInt32.max.

要生成 0.0 到 300.0 范围内的 Double(小数点后有一位):

Double(arc4random_uniform(3001))/10.0

您可以将其扩展到更多小数位。对于两位小数(0.00 到 300.00):

Double(arc4random_uniform(30001))/100.0

三位小数(0.000 到 300.000):

Double(arc4random_uniform(300001))/1000.0

这具有能够实际生成整数值的优点。在第一种情况下,10% 的数字将是整数。在第二种情况下,1% 的数字将是整数。在第三个中,0.1% 的数字将是完整的。

这是你的功能,我相信:

extension Double {

/// Generates a random `Double` within `0.0...1.0`
public static func random() -> Double {
    return random(0.0...1.0)
}

/// Generates a random `Double` inside of the closed interval.
public static func random(interval: ClosedInterval<Double>) -> Double {
    return interval.start + (interval.end - interval.start) * (Double(arc4random()) / Double(UInt32.max))
}

}

用法示例:

Double.random(0...300)

它取自 RandomKit 库 - 它看起来对各种用途都非常有用。