To generate a random number in C, you need to call two functions in the stdlib. h header file:
Int rand (void): generates a random integer between 0 and RAND_MAX. (RAND_MAX is defined in stdlib. h and its value is 2147483647)
Void srand (int seed): used to initialize the seed, so that different random numbers are generated each time.
Code snippet:
Copy to ClipboardReference: [www.bkjia.com] # include <stdio. h>
# Include <stdlib. h>
Int main (int argc, char * argv [])
{
Int I;
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand ());
}
Return 0;
}
Code snippet:
Copy to ClipboardReference: [www.bkjia.com]/*
The random numbers generated by the preceding method are different each time, but the order of the random numbers generated during each operation is the same. The reason is that each time the seeds are the same, the same random sequence is generated. Generally, time is used as the seed to ensure that each seed is different. Simple implementation code:
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
Int main (int argc, char * argv [])
{
Int I;
Srand (int) time (0 ));
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand ());
}
Return 0;
}
Code snippet:
Copy to ClipboardReference: [www.bkjia.com]/*
If you want to generate integers in other ranges, you can use the remainder operation. The following code generates 0 ~ Random numbers between 100:
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
Int main (int argc, char * argv [])
{
Int I;
Srand (int) time (0 ));
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand () %100 );
}
Return 0;
}