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

Random.nextInt(74)

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


当前回答

我想我可以添加一个我在许多项目中使用的方法。

- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
    return (NSInteger)(min + arc4random_uniform(max - min + 1));
}

如果我最终在许多文件中使用它,我通常声明一个宏为

#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))

E.g.

NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74

注意:仅适用于iOS 4.3/OS X v10.7 (Lion)及更高版本

其他回答

//下面的例子将生成一个0到73之间的数字。

int value;
value = (arc4random() % 74);
NSLog(@"random number: %i ", value);

//In order to generate 1 to 73, do the following:
int value1;
value1 = (arc4random() % 73) + 1;
NSLog(@"random number step 2: %i ", value1);

输出:

随机数:72 随机数字步骤2:52

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

int x = arc4random()%100;

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

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

这会给你一个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);

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

arc4random_uniform(74)

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

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

我想我可以添加一个我在许多项目中使用的方法。

- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
    return (NSInteger)(min + arc4random_uniform(max - min + 1));
}

如果我最终在许多文件中使用它,我通常声明一个宏为

#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))

E.g.

NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74

注意:仅适用于iOS 4.3/OS X v10.7 (Lion)及更高版本