How to generate random numbers in C/C ++
How to generate random numbers in C/C ++: here we use the rand () function, the srand () function, and the C/C ++ function without the built-in random (INT number) function.
(1) If you only need to generate a random number without setting a range, you only need to use rand (): rand () returns a random value, the value range is 0 to rand_max. Rand_max is defined in stdlib. h and its value is 2147483647.
For example:
# Include <stdio. h>
# Include <stdlib. h>
Void main ()
{
For (INT I = 0; I <10; I +)
Printf ("% d \ n", Rand ());
}
(2) If you want to generate a random number in a certain range, you can define a random (INT number) function in the macro definition, and then directly call random () in main () function:
For example, a random generation of 10 0 ~ Number of 100:
# Include <stdio. h>
# Include <stdlib. h>
# Define random (x) (RAND () % x)
Void main ()
{
For (INT x = 0; x <10; X ++)
Printf ("% d \ n", random (100 ));
}
(3) However, the random numbers generated in the preceding two examples can only be one-time. If the output result is the same as that of the first running. This is related to the srand () function. Srand () is used to set the random number seed when rand () generates a random number. Before calling the rand () function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set () during the call, the random seed is set to 1. In the above two examples, because no random number seed is set, each random number seed is automatically set to the same value of 1, which leads to the same random value produced by rand.
Srand () function definition: void srand (unsigned int seed );
Generally, the return value of geypid () or time (0) can be used as seed.
If you use time (0), add the header file # include <time. h>
For example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
# Define random (x) (RAND () % x)
Void main ()
{
Srand (INT) time (0 ));
For (INT x = 0; x <10; X ++)
Printf ("% d \ n", random (100 ));
}
In this way, the two running results will be different !!
Author: aillo. When reprinting this article, the original source of the article must be indicated in the form of hyperlinks!
Web: http://www.ezloo.com/2008/03/cc_random.html