[C language library function source code]
[This program is compiled in Dev C ++ 4.9.9.2]
/*
These two functions are programs that generate random numbers in the C library. You need to first
Use the srand () function to assign a random seed value. And then use
Rand () function to generate a random number. But the algorithm that generates random numbers
Relatively simple, the srandom () and random () functions are for these two functions
And the usage is similar.
*/
# Define random_max 0x7fffffff
Static long my_do_rand (unsigned long * value)
{
/*
This algorithm ensures that the generated value does not exceed (2 ^ 31-1)
Here (2 ^ 31-1) is 0x7fffffff. 0x7fffffff
Equal to 127773*(7 ^ 5) + 2836,7 ^ 5 = 16807.
The entire algorithm is through: t = (7 ^ 5 * t) mod (2 ^ 31-1)
This formula is used to calculate the random value and take the obtained value
The Random Seed value calculated next time.
*/
Long quotient, remainder, T;
Quotient = * value/127773l;
Remainder = * value % 127773l;
T = 16807l * remainder-2836l * quotient;
If (T <= 0)
T + = 0x7fffffffl;
Return (* value = T) % (unsigned long) random_max + 1 ));
}
Static unsigned long next = 1;
Int my_rand (void)
{
Return my_do_rand (& next );
}
Void my_srand (unsigned int seed)
{
Next = seed;
}
# Include <time. h>
Int main ()
{
Int I;
My_srand (unsigned) (Time (null )));
For (I = 0; I <100; I ++)
{
If (I % 10 = 0)
Printf ("/N ");
Printf ("% d/T", my_rand () % 99 + 1 );
}
System ("pause ");
Return 0;
}