通过读取 /dev/urandom 设备文件可以更快更好更“随机”的产生随机数,比如下面代码:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
FILE *urandom;
unsigned int seed;
int i;
urandom = fopen ("/dev/urandom", "r");
if (urandom == NULL) {
fprintf (stderr, "Cannot open /dev/urandom!\n");
exit (EXIT_FAILURE);
}
for (i = 0; i < 10; i++) {
fread (&seed, sizeof (seed), 1, urandom);
srand (seed);
printf ("Random number from 1 to 100: %d\n", (int) floor (rand() * 100.0 / ((double) RAND_MAX + 1) )+ 1);
}
return 0;
}
编译运行输出:# gcc urandom.c -o urandom -lm
# ./urandom
Random number from 1 to 100: 21
Random number from 1 to 100: 78
Random number from 1 to 100: 45
Random number from 1 to 100: 3
Random number from 1 to 100: 60
Random number from 1 to 100: 41
Random number from 1 to 100: 91
Random number from 1 to 100: 62
Random number from 1 to 100: 97
Random number from 1 to 100: 5 使用数学函数库时,在编译时要注意使用 -lm 选项。 |