曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4220|回复: 0
打印 上一主题 下一主题

使用 /dev/urandom 产生更好的随机数

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2012-6-17 20:55:21 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
通过读取 /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 选项。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-3 13:08 , Processed in 0.080550 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表