使用随机的C代码说明

时间:2014-09-13 22:26:36

标签: objective-c c

以下代码在obj-C中做了什么 - 它如何得到介于0和1之间的数字?

float prob = (arc4random() % 100) / 100.0

3 个答案:

答案 0 :(得分:3)

来自OS X manual

DESCRIPTION
 The arc4random() function uses the key stream generator employed by the
 arc4 cipher, which uses 8*8 8 bit S-Boxes.  The S-Boxes can be in about
 (2**1700) states.  The arc4random() function returns pseudo-random num-bers numbers
 bers in the range of 0 to (2**32)-1, and therefore has twice the range of
 rand(3) and random(3).

 The arc4random_stir() function reads data from /dev/urandom and uses it
 to permute the S-Boxes via arc4random_addrandom().

 There is no need to call arc4random_stir() before using arc4random(),
 since arc4random() automatically initializes itself.

答案 1 :(得分:1)

The arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1

Source

它生成一个u_int32_t随机数。模数为100可使其在0到99范围内(尽管可能低于99)。它将此结果除以0到1的范围。

所以如果要做3006:

3006 % 100 = 6
6 / 100.0 = 0.06

答案 2 :(得分:1)

arc4random()会返回u_int32_t整数
mod('%' aka余数运算符)并将整数减少到0 - 99范围内 除以100.0(浮点数)将强制转换为浮点并返回浮点数0.00 - 0.99。

更好,因为它消除了舍入偏差:

float prob = (arc4random_uniform(100) / 100.0;

注意:arc4random()及其变体会生成加密安全随机数。它不需要手动播种。