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

Random.nextInt(74)

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


当前回答

//下面的例子将生成一个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到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);

对于游戏开发,使用random()生成随机变量。可能至少比使用arc4random()快5倍。模偏不是一个问题,特别是在游戏中,当使用random()的全范围生成随机时。一定要先播种。在AppDelegate中调用srandomdev()。下面是一些辅助函数:

static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}

从iOS 9和OS X 10.11开始,你可以使用新的GameplayKit类以各种方式生成随机数。

你有四种源类型可以选择:一般随机源(未命名,直到系统选择它做什么),线性同余,ARC4和梅森扭扭。它们可以生成随机int型、浮点型和bool型。

在最简单的层面上,你可以从系统内置的随机源生成一个随机数,如下所示:

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

这就产生了一个介于- 2147,483,648到2147,483,647之间的数字。如果你想要一个介于0和上界(不包含)之间的数字,你可以使用这个:

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit内置了一些方便的构造函数来处理骰子。例如,你可以像这样掷一个六面骰子:

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

此外,你还可以使用GKShuffledDistribution之类的东西来塑造随机分布。

和C一样

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

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

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

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

int x = arc4random()%100;

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

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