简体   繁体   中英

How do I generate random numbers on iOS?

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.

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

int r = arc4random() % 5;

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

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

srand(time(0));

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

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

随机数生成的简单功能:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM