Method for generating random Numbers in objective c

  • 2020-05-10 22:58:20
  • OfStack

This paper briefly describes several common methods of generating random Numbers in objective-c and shares them with you in the hope of providing you with 1 reference value. The details are as follows:

1) arc4random() method: it is more accurate and does not need to generate random seeds

Usage:

The code for getting integers between 0 and x-1 through arc4random() is as follows:


 int value = arc4random() % x;

The code to get the integer between 1 and x is as follows:


 int value = (arc4random() % x) + 1;

2), CCRANDOM_0_1() method: used in cocos2d, the scope is [0,1]

Usage:


 float random = CCRANDOM_0_1() * 5; //[0,5]  CCRANDOM_0_1()  The range is [0,1]

3) random() method: seed is set when initialization is required

Usage:


srandom((unsigned int)time(time_t *)NULL); // When you initialize, set the seed. 

The code in this article has more detailed comments, I believe it is not difficult to understand. If you are interested, you can do it yourself.


Related articles: