The cocos2d-x provides a method for generating random numbers.CCRANDOM_0_1
The specific definition is as follows.
/** @def CCRANDOM_0_1 returns a random float between 0 and 1 */#define CCRANDOM_0_1() ((float)rand()/RAND_MAX)
It can be seen that it returns a 0 ~ Random number between 1.
In the same way,
1. int random = CCRANDOM_0_1 () + 1; generate 1 ~ Random Number between 2
2. int random = CCRANDOM_0_1 () * 100; 0 ~ Random Number between 100
However, the cocos2d-x uses the rand () function,
Rand () Usage
Rand () does not require a parameter. It returns an arbitrary integer from 0 to the maximum random number. The maximum random number is usually a fixed large integer. In this way, if you want to generate 0 ~ 10 integers, which can be expressed:
Int N = rand () % 11;
In this way, the value of N is a 0 ~ A random number of 10 ~ 10, it is like this:
Int N = 1 + rand () % 11;
In summary, it can be expressed:
A + rand () % n
Where a is the starting value and n is the range of integers. A + rand () % (B-a + 1) indicates ~ If a random number between B is 0 ~ 1 decimal point, you can first get 0 ~ Then, divide all the values by 10 to get the 10 random decimal places from random to very. To get the random decimal places from random to percentile, you must first get 0 ~ The 10 Integers of 100 are all divided by 100. In other cases, this is the case.
Generally, the random numbers generated by rand () are the same as the previous one during each operation. This design is intended to facilitate program debugging. To generate different random numbers each time, you can use the srand (seed) function for randomization. Different random numbers can be generated as the seed varies.
Therefore, processing can also contain time. h header file, and then use srand (time (0) to use the current time to randomize the random number generator, in this way, different random number sequences can be obtained every two runs (as long as the interval between two runs exceeds 1 second ).
To sum up, the CCRANDOM_0_1 () is not random. We recommend that you use the arc4random () function (you do not need to initialize random seeds and can directly use them ).
In addition, there are three methods for generating random numbers in objective-c: arc4random (), CCRANDOM_0_1 (), and random:
1) arc4random () is more accurate and does not need to generate random seeds.
Usage:
The code for getting an integer between 0 and X-1 through arc4random () is as follows:
Int value = arc4random () % x;
The code for getting an integer between 1 and x is as follows:
Int value = (arc4random () % x) + 1;
2) CCRANDOM_0_1 () is used in cocos2d. The value range is [0, 1].
Usage:
Float random = CCRANDOM_0_1 () * 5; // [] CCRANDOM_0_1 () value range: []
3) set the seed when random () needs Initialization
Usage:
Srandom (unsigned int) time (time_t *) NULL); // set the Random Seed during initialization.