在0和1之间快速浮动 [英] Swift random float between 0 and 1

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

问题描述

在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
}

I '获取'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之间快速浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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