Random number between two decimals in Swift

2019-01-26 07:59发布

I'd like to get a random number between two small decimal numbers.

Between maybe 0.8 and 1.3.

var duration = CGFloat(arc4random() % 0.8) / 1.3

or

var duration = CGFloat(arc4random() % 0.5) + 0.8

Thanks!

标签: ios random swift
1条回答
对你真心纯属浪费
2楼-- · 2019-01-26 08:39

Here's a generic function I just wrote up quickly to get a random number within a range.

func randomBetween(_ firstNum: CGFloat, _ secondNum: CGFloat) -> CGFloat{
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

It takes a random number, finds the remainder of that number divided by the difference between the two parameters, then adds by the smaller number. This guarantees the random number to be between the two numbers.

Disclaimer: I have not tested this out yet.

EDIT: Now this function does what you want.

查看更多
登录 后发表回答