0 到 1 之间的 Swift 随机浮点数 [英] Swift random float between 0 and 1

查看:17
本文介绍了0 到 1 之间的 Swift 随机浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,我试图获得一个介于 0 和 1 之间的随机浮点数,但我似乎无法使类型转换起作用.

In Swift, I'm trying to get a random float between 0 and 1 but I can't seem to get the type conversions to work.

func randomCGFloat() -> CGFloat {
    return CGFloat(arc4random()) / UINT32_MAX
}

我收到CGFloat"无法转换为UInt8"错误

I'm getting a 'CGFloat' is not convertible to 'UInt8' error

运行 Xcode 6.

Running Xcode 6.

推荐答案

尝试将除数初始化为浮点数,la:

Try initializing the divisor as a float as well, a la:

CGFloat(Float(arc4random()) / Float(UINT32_MAX))

这篇关于0 到 1 之间的 Swift 随机浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆