use*_*792 1 c random floating-point arc4random
可能重复:
如何生成0到1之间的随机浮点数?
我想生成0到1之间的随机数(均匀分布),我使用:
float x = arc4random_uniform(1);
Run Code Online (Sandbox Code Playgroud)
但是,这只产生0.00000
我用了
float y = arc4random() %11 * 0.1;
Run Code Online (Sandbox Code Playgroud)
在区间内返回一个随机数,但我不确定它是否是均匀分布.
为什么第一个功能不按预期工作?
小智 5
我用:
float x = arc4random_uniform(1);
Run Code Online (Sandbox Code Playgroud)
但是,这只产生0.00000
当然可以.arc4random_uniform()
返回一个32位无符号整数.它没有返回float
.您正在寻找的是类似的东西
#define RAND_PRECISION 1024
float x = arc4random_uniform(RAND_PRECISION) / (float)RAND_PRECISION;
Run Code Online (Sandbox Code Playgroud)
也,
我不确定它是否是均匀分布.
既然不是.使用modulo(%
)运算符会导致非均匀分布.