我主要是一个Java头,我想要一种方法来生成0到74之间的伪随机数。在Java中,我会使用这种方法:
Random.nextInt(74)
我对讨论种子或真正的随机性不感兴趣,我只关心如何在Objective-C中完成相同的任务。我搜索了谷歌,似乎有很多不同的和相互矛盾的信息。
我主要是一个Java头,我想要一种方法来生成0到74之间的伪随机数。在Java中,我会使用这种方法:
Random.nextInt(74)
我对讨论种子或真正的随机性不感兴趣,我只关心如何在Objective-C中完成相同的任务。我搜索了谷歌,似乎有很多不同的和相互矛盾的信息。
当前回答
生成0到99之间的随机数:
int x = arc4random()%100;
生成500到1000之间的随机数:
int x = (arc4random()%501) + 500;
其他回答
已经有一些很好的、清晰的答案了,但这个问题要求的是0到74之间的一个随机数。使用:
arc4random_uniform (75)
//下面的例子将生成一个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
最好使用arc4random_uniform。但是,这在iOS 4.3以下是不可用的。幸运的是,iOS会在运行时绑定这个符号,而不是在编译时绑定(所以不要使用#if预处理器指令来检查它是否可用)。
确定arc4random_uniform是否可用的最好方法是这样做:
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (74);
else
r = (arc4random() % 74);
生成0到99之间的随机数:
int x = arc4random()%100;
生成500到1000之间的随机数:
int x = (arc4random()%501) + 500;
我想我可以添加一个我在许多项目中使用的方法。
- (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)及更高版本