使用兰特产生一个随机数 [英] using rand to generate a random numbers

查看:92
本文介绍了使用兰特产生一个随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.4.4 C89

gcc 4.4.4 c89

我用下面的code。不过,我不断收到同一个号码:

I am using the code below. However, I keep getting the same number:

    size_t i = 0;

    for(i = 0; i < 3; i++) {
        /* Initialize random number */
        srand((unsigned int)time(NULL));
        /* Added random number (simulate seconds) */
        add((rand() % 30) + 1);
    }

我想获得0至30返回。不过,我最后一次跑这我得到了17三次。

I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times.

非常感谢,

推荐答案

您正在播种的 的内侧的环(与由于循环将如何快速地被执行的相同的值),这将导致产生的随机数是相同的,每次

You're seeding inside the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.

您需要将您的种子功能的 的外循环:

You need to move your seed function outside the loop:

/* Initialize random number */
srand((unsigned int)time(NULL));

for(i = 0; i < 3; i++) {
    /* Added random number (simulate seconds) */
    add((rand() % 30) + 1);
}

这篇关于使用兰特产生一个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆