banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

Different Random Number Algorithms in Objective-C for iOS Development (arc4random, random, srandom)

Objective-C does not directly provide functions or methods for generating random data. However, we can directly use various random algorithms in C. The following are several common random number algorithms that can be referenced using the stdlib.h header file.

arc4random does not require a random seed and automatically generates a random seed when called. Returns a set of [0, X) int value = arc4random() % x; Returns a set of [1, X] int value = (arc4random() % x) + 1;

random()/rand() does not use a seed and returns any number within the long/int range. Note that random returns long and rand returns int.

srandom(unsigned)/srand(unsigned) uses a random seed and returns any number between the parameter and RAND_MAX. Note that srandom can use unsigned long as a parameter.

It is important to note that the rand series of random numbers use pseudo-random algorithms, so it is recommended to use different random seeds when calling them. For example: srand(time(NULL))

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.