Arc4random浮动?

问题描述

| 这样做:
float x = arc4random() % 100;
返回0到100之间的数字的体面结果。 但是这样做:
float x = (arc4random() % 100)/100;
返回0。如何获取返回浮点值的值?     

解决方法

        简而言之,您正在执行整数除法,而不是浮点除法,因此您只是得到了被截断的结果(例如,.123被截断为0)。尝试
float x = (arc4random() % 100)/100.0f;
    ,        您将一个整数除以一个整数,从而得到一个整数。您需要将其中之一强制转换为浮点数:
float x = (arc4random() % 100)/(float)100;
另请参阅我对模运算符的评论。     ,        在Swift中:
Float(arc4random() % 100) / 100
    ,        要获得浮点除法而不是整数除法:
float x = arc4random() % 100 / 100.f;
但是要小心,使用
% 100
只会得到0到99之间的值,因此将其除以100.f只会产生0.00f到0.99f之间的随机值。 更好的是,获得介于0和1之间的随机浮点数:
float x = arc4random() % 101 / 100.f;
更好的是,避免模量偏差:
float x = arc4random_uniform(101) / 100.f;
最好,以避免精度偏差:
float x = (float)arc4random() / UINT32_MAX;
我相信Swift将是:
let x = Float(arc4random()) / UINT32_MAX
    ,        在Swift 4.2中,它变得更加舒适 0至100之间
Float.random(in: 0.0...100.0)
在0和1之间
Float.random(in: 0.0...1.0)