我主要是一个Java头,我想要一种方法来生成0到74之间的伪随机数。在Java中,我会使用这种方法:

Random.nextInt(74)

我对讨论种子或真正的随机性不感兴趣,我只关心如何在Objective-C中完成相同的任务。我搜索了谷歌,似乎有很多不同的和相互矛盾的信息。


当前回答

已经有一些很好的、清晰的答案了,但这个问题要求的是0到74之间的一个随机数。使用:

arc4random_uniform (75)

其他回答

生成0到99之间的随机数:

int x = arc4random()%100;

生成500到1000之间的随机数:

int x = (arc4random()%501) + 500;

和C一样

#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;

(假设您的意思是包括0但不包括74,这就是您的Java示例所做的)

编辑:请随意用random()或arc4random()代替rand()(正如其他人指出的那样,这非常糟糕)。

已经有一些很好的、清晰的答案了,但这个问题要求的是0到74之间的一个随机数。使用:

arc4random_uniform (75)

使用arc4random_uniform(upper_bound)函数生成一个范围内的随机数。下面将生成一个0到73之间的数字。

arc4random_uniform(74)

Arc4random_uniform (upper_bound)避免模偏置,如手册页所述:

Arc4random_uniform()将返回一个小于upper_bound的均匀分布随机数。建议使用Arc4random_uniform()而不是arc4random() % upper_bound这样的结构,因为当上界不是2的幂时,它可以避免“模偏置”。

这会给你一个0到47之间的浮点数

float low_bound = 0;      
float high_bound = 47;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

或者只是简单的

float rndValue = (((float)arc4random()/0x100000000)*47);

下限和上限也可以是负的。下面的示例代码给出了一个介于-35.76和+12.09之间的随机数

float low_bound = -35.76;      
float high_bound = 12.09;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

将结果转换为整数值:

int intRndValue = (int)(rndValue + 0.5);