"Programming Development" C language random number Rand usage precautions
Disclaimer: Reference Please specify source http://blog.csdn.net/lg1259156776/
Note: The random number is very important in programming development, in the case of the RAND function in C, it is necessary to pay attention to where random numbers are randomly represented, for example, if the program executes at different times, whether the random number in the same position needs to be the same, or the random number to be generated each time, etc. These are places that need to be watched.
The test shows that the random number generated by each run is the same without the use of the Srand random number seed: Sometimes it is necessary to use Srand, of course, can be used directly to operate, in some places need to fix some random number, you can give Srand auxiliary with the same parameters, then he generated a random sequence is the same;
#include<stdio.h>#include<stdlib.h>#include<time.h>void main(int seed){ int i, num; srand((unsigned int)time(NULL)); for(i = 0; i < 10; i++) { num = rand()%100; printf("%d ",num); } printf("\n"); printf("This is a hello world!\n");}
The following code can refer to, when the same random number seed is set, the resulting random sequence is the same:
#include<stdio.h>#include<stdlib.h>#include<time.h>void main(int seed){ int i, num;// srand((unsigned int)time(NULL)); srand(1000); for(i = 0; i < 10; i++) { num = rand()%100; printf("%d ",num); } printf("\n"); srand(2000); for(i = 0; i < 10; i++) { num = rand()%100; printf("%d ",num); } printf("\n"); srand(1000); for(i = 0; i < 10; i++) { num = rand()%100; printf("%d ",num); } printf("\n"); printf("This is a hello world!\n");}
Of course, to ensure that the random number generated at each run is different, it is better to call the time function to initialize the random number seed according to the timing of execution, so that it is well guaranteed that each execution will produce a distinct random number.
2015-11-06 Debug Record Zhang Bongyi
Copyright NOTICE: This article for Bo Master original article, reprint please indicate source http://blog.csdn.net/lg1259156776/.
"Programming Development" C language random number Rand usage precautions