rand()返回相同的数字 [英] rand() return the same number

查看:169
本文介绍了rand()返回相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用rand()在C语言中做一个简单的例子,但是即使我使用srand(),该函数也总是返回相同的数字.

I am making a simple example in C with rand() but the function always return the same number despite i am using srand().

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int generate(int min, int max)
{
    srand(time(NULL));
    return rand() % (max - min + 1) + min;
}

int main()
{
    int i;
    for (i = 0; i < 10; i++)
    {

        printf("Number random %d = %d\n", i, generate(1, 100));
    }

    return 0;
}

执行:

随机数0 = 40随机数1 = 40随机数2 = 40随机数 随机数3 = 40随机数4 = 40随机数5 = 40随机数 6 = 40个随机数7 = 40个随机数8 = 40个随机数9 = 40

Number random 0 = 40 Number random 1 = 40 Number random 2 = 40 Number random 3 = 40 Number random 4 = 40 Number random 5 = 40 Number random 6 = 40 Number random 7 = 40 Number random 8 = 40 Number random 9 = 40

推荐答案

这是因为您每次都在播种,并且由于程序运行速度非常快,因此每次调用的种子值(time())相同因为它的最小增量是1秒.

It is because you are reseeding it every time, and as your program probably runs very quickly, your seed value (time()) is the same for each call as it's smallest increment is 1 second.

尝试将srand()移到main()并调用一次

这篇关于rand()返回相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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