Today we see a small program that uses random numbers. It was found that generating random numbers in C was not as simple as in MATLAB.
There is also the rand () function in C, but the number produced by the rand () function is not a random number in the true sense, a pseudo-random number, a series of numbers derived from a recursive formula based on a number, which we call a seed. The range is between 0~rand_max. Rand_max and Rand () are also defined in stdlib.h with a value of at least 32767. The seed is fixed when the computer boots up normally. So if you do not combine other functions, using rand () produces random numbers with the following conditions:
1#include <stdlib.h>2 intMain ()3 {4 inti,j;5 for(i=0;i<Ten; i++)6 {7j=1+(int) (rand ()%Ten);8printf"%d", j);9 } Ten}
You will find that the result of the program executing n times is the same, because if the random number seed is not set, rand () will default the random number seed to 1 when it is called. To solve this problem, C provides the Srand () function. Therefore, you must call Srand () to set the seed before calling Rand () to produce a random number. The prototype of Srand () is void srand (int a). In conjunction with the use of Srand () we write a program that generates random numbers:
#include <stdio.h>#include<stdlib.h>#include<time.h>intMain () {Srand (int) Time (0)); inti; for(i=0; i<!0; i++) {printf ("%d",(int) (rand ()%Ten)); } printf ("\ n");}
[Email protected]:/home/qj/python_pro#./Test5 6 2 3 8 6 1 9 8 0[email protected]:/home/qj/python_pro#./Test5 6 1 7 6 0 9 8 0 2[email protected]:/home/qj/python_pro#./Test1 1 6 2 6 1 6 5 1 0[email protected]:/home/qj/python_pro#./Test9 4 0 3 0 7 8 7 0 1[email protected]:/home/qj/python_pro#./Test8 2 1 5 4 0 2 9 5 2[email protected]:/home/qj/python_pro#./Test6 1 9 6 8 2 6 2 1 1[email protected]:/home/qj/python_pro#./Test2 1 0 4 0 8 9 0 7 2[email protected]:/home/qj/python_pro#./Test7 4 9 3 1 7 6 4 1 0[email protected]:/home/qj/python_pro#./Test4 8 1 1 1 2 6 3 3 0[email protected]:/home/qj/python_pro#
where time () is used to obtain machine times, it is defined in time.h.
Because program execution is random, system time also has randomness. So we can get the seeds with randomness, and use Srand () to set the seed once each time we use the rand () function, so we can get a random number.
You can also refer to:
http://Wenku.baidu.com/link?url=ucsvyyznnaoxlvuiqhgjppcbl6jlcpxmpxahyzep_ Epmdxb977nqqtk-daed7k7-kjj9v90bn6n0a-p1rfagi9dvn0wsvy04kf8-l34dxn_
How to generate random numbers in C language