如何在iOS上生成随机数?

时间:2022-08-17 09:08:45

What is the best way to generate random numbers using Objective-C on iOS?
If I use (int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0) to generate a number from 0 to 4, every time I start the program on the iPhone it generates the same numbers to start off with.

在iOS上使用Objective-C生成随机数的最佳方法是什么?如果我使用(int)((double)rand()/((double)(RAND_MAX)+(double)1)* 5.0)生成一个从0到4的数字,每次我在iPhone上启动程序时它会生成相同的数字开始。

6 个解决方案

#1


There is a very similar question here on *. Here is one of the better solutions (no need for seeding):

*上有一个非常类似的问题。这是一个更好的解决方案(不需要播种):

int r = arc4random() % 5;

#2


i use

#define RANDOM_SEED() srandom(time(NULL))
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))

so you can give a min and max

所以你可以给出最小值和最大值

#3


You should seed the random number generator with the current time.

您应该使用当前时间为随机数生成器播种。

srand(time(0));

#4


How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().

你需要多随机?如果你想要足够随机加密,那么使用SecRandomCopyBytes()。

#5


Call srand() at the start of your program, it'll reseed random number generator

在程序开始时调用srand(),它将重置随机数生成器

#6


Simple function for random number generation:

随机数生成的简单功能:

int r = arc4random() % 42;  // generate number up to 42 (limit)

#1


There is a very similar question here on *. Here is one of the better solutions (no need for seeding):

*上有一个非常类似的问题。这是一个更好的解决方案(不需要播种):

int r = arc4random() % 5;

#2


i use

#define RANDOM_SEED() srandom(time(NULL))
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))

so you can give a min and max

所以你可以给出最小值和最大值

#3


You should seed the random number generator with the current time.

您应该使用当前时间为随机数生成器播种。

srand(time(0));

#4


How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().

你需要多随机?如果你想要足够随机加密,那么使用SecRandomCopyBytes()。

#5


Call srand() at the start of your program, it'll reseed random number generator

在程序开始时调用srand(),它将重置随机数生成器

#6


Simple function for random number generation:

随机数生成的简单功能:

int r = arc4random() % 42;  // generate number up to 42 (limit)