The Srand () and Rand () functions in the C standard library strlib can be used to generate random numbers, but the rand () function can only generate integers [0, Rand_max], Rand_max defined differently on different machines, On my machine is 0x7fff (i.e. 32767), and the following implements its own extensible random () function:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//My_rand (): Return uniform Random number in [0, 1]
double My_rand () {
//rand (): Return uniform random number in [0, Rand_max]
return (d ouble) rand ()/Rand_max;
}
int random (int min, int max) {
return (int) (My_rand () * (max-min) + min);
}
int main () {
int min = 5;
int max =;
int i = 0;
int n = +;
Srand (Time (NULL));
while (I < n) {
int r = random (min, max);
printf ("%d", r);
if (R < 5 | | r >) {
printf ("error!\n");
break;
}
i++;
}
printf ("\ n");
return 0;
}
Reference: Rujia "Introduction to Algorithmic Competition" section 6.2