曲径通幽论坛

标题: 使用 /dev/urandom 产生更好的随机数 [打印本页]

作者: beyes    时间: 2012-6-17 20:55
标题: 使用 /dev/urandom 产生更好的随机数
通过读取 /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 选项。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2