执行此操作:
float x = arc4random() % 100;返回介于0和100之间的数字的适当结果。
但是这样做:
float x = (arc4random() % 100)/100;返回0。我怎样才能让它返回一个浮点值?
发布于 2011-06-01 06:03:58
简单地说,您正在进行整数除法,而不是浮点除法,因此您只会得到一个截断的结果(例如,.123被截断为0 )。试一试
float x = (arc4random() % 100)/100.0f;发布于 2011-06-01 06:04:54
你用一个int除以一个int,得到一个int。您需要将任一项强制转换为浮点数:
float x = (arc4random() % 100)/(float)100;另请参阅我对模运算符的评论。
发布于 2016-01-13 19:20:25
要获得浮点除法而不是整数除法,请执行以下操作:
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 4.2+中,您可以获得对范围的内置支持:
let x = Float.random(in: 0.0...1.0)https://stackoverflow.com/questions/6194062
复制相似问题