Many people prefer to use rand ()%n to produce a random integer within the interval [0,n]. Regardless of whether the resulting integer is still evenly distributed, this method does not get the desired result when n is greater than Rand_max. Since Rand_max is likely to be only 32767 so small, you should be careful when using this method.
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int n=100,m=1000;
Double random ()
{return
(double) rand ()/rand_max;
}
Random numbers that produce [0,m-1] closed intervals
double random (int m)
{return
(int) (Random () * (m-1) +0.5);
}
int main ()
{
Srand (Time (NULL)); Initialize random number seed
//The program uses a different seed each time it executes, so the Srand is invoked in time.h for parameters. The
function return value is the number of seconds that have elapsed since 0 o'clock January 1, 1970.
*
// printf ("Rand_max:%d\n", Rand_max);
printf ("%d%d\n", m,n);
for (int i=0;i<m;i++)
{
if (rand ()%2==0) printf ("A");
else printf ("B");
int x,y;
for (;;)
{
x=random (n) +1;
Y=random (n) +1;
if (x!=y) break;
printf ("%d%d\n", x,y);
}
return 0;
}
/* The
RAND () in the core functional Stdlib.h (), which generates a uniform random integer for a closed interval [0,rand_max] (even meaning that each integer in the interval
has the same probability of being produced), where the Rand_max is at least 32767 (2^ 15-1), the values may be different in different environments. Strictly speaking,
the random number here is "pseudo random number", because it is also calculated by the mathematical formula, but in the algorithm field, in most cases it can be regarded as
a real random number.
*/
The above code takes the approach of dividing by Rand_max, getting the random real number between [0,1], expanding n-1 times, rounding, and adding 1 to get a uniform integer between [1,n]. In this case, when n is very large, "precision" is not good (as if to enlarge the image of the "sawtooth"), but here is small, this can be enough to meet the requirements.
The program first executes a srand (Time (NULL)) where the Srand function initializes the random number seed. Simply put, the seed is the basis of the pseudo random number calculation. The same seed, the calculated "random number" sequence is always the same. If you use RAND () without invoking Srand, it is equivalent to calling Srand (1) Once, so each time the program executes, it gets the same set of random numbers. Also, do not recall srand once for each random number generated by the same program. Some beginners complain that "rand () produces random numbers that are not random at all" because of the misunderstanding of the role of Srand ()-Again, please call only once srand at the beginning of the program, not multiple calls in the same program.