The simple code that generates 0~100 random numbers is as follows:
#include <stdio.h>
#include <time.h>
void Main ()
{
int i=0,j=0;
int p;
Srand (NULL),//Generation time seed
P=rand ()%100+1;//generate random number
printf ("%d\t", p);
printf ("\ n");
}
in the above code we can see that three functions are used, namely srand,rand and time functions.
The function of Srand () is to provide a seed whose function format is void srand (unsigned int seed). Seed here we call it the time seed, and if it is not srand, the time seed does not change, thus the random number produced by Rand () never changes.
Then call Rand () with the format int rand (void). It returns a random number (between 0 and 32767) based on the seed value provided to Srand (), and we can vary the range by operation according to our own needs.
The time () function is to produce a positive integer, which is the number of seconds elapsed since 00:00:00 January 1, 1970. Here we have to worry about the size of a positive integer, in fact, is more. The limit of the INT type variable 2147483647 is the time of 2038-01-19 11:14:7. So we don't have to worry about that. And now the time_t structure is signed int 32, or 32 bits. This problem can be solved with the upgrade to 64 digits.
About the Time.h header file will be introduced in the next blog post.