Recently wanted to write a 1a2b small game to practice, the result in the first step to generate random numbers when you encounter a little bit of a problem.
The game needs to be initialized with a four-bit random number, and each of you is not equal. So the first idea is to generate an array of integers, just to determine whether the generated random number with the previous number is duplicated, there is regeneration can, but then found two problems. The first is that the random number generated after each invocation of the function is the same. Second, the generated random number, if 0 is the first, is discarded when the itoa function is called.
Later the study found that the reason for this is that Srand is placed in the function, and each call to the function resets the random number seed to the initial value, and the resulting random number is the same. As for the second mistake, it can be cleverly avoided in another way. The code is as follows:
Sir, make an array of integers of 0-9, and then randomly take a number from it, as long as it is not equal to 1, it is taken out to the random number to be generated and the position is-1. This can also be a little more efficient, rather than deleting array members.
1/****************************************************************************** 2 * function name: void GetRandom (char * Random) 3 * Function: Produces a number of unequal four-bit random number 4 * Entry parameters: Random for the returned number of 5 * return value: No 6 * Remarks: Sir, as an array of integers of 0-9, and then randomly take four numbers from it, Each takes a position of-1 7 *******************************************************************************/ 8 void Getrandom (char * random) {9 int i, j[10], k;10 for (i = 0; i <; i++) {one j[i] = i;12 }13 for (i = 0; I < 4; i++) { +//Generate the I-random number k = (int) rand ()% 10;//k is subscript ( j[k] = = 1) { k = (k + 1)%; random[i] = ' 0 ' + j[k];20 j[k] = -1;21 }22}
C\c++ generate random numbers that are not equal to the number of members