rand()在多个函数调用中是一致的 [英] rand() is consistent across multiple function calls

查看:148
本文介绍了rand()在多个函数调用中是一致的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从函数调用中产生2个随机数时,我得到了重复的结果。然而, rand()函数可以在循环中正常工作,或者它们不在函数调用之外。 / p>

我猜这是因为系统时间和程序很小。但我不知道如何改变种子。

  #include< stdio.h> 
#include< ctype.h>
#include< string.h>

int test1(){

int randX,randY;
int range = 5;

srand(time(NULL));

randX =(rand()%range)+ 1;

randY =(rand()%15)+ 1;
printf(X:%d Y:%d \\\
,randX,randY);
}

int main(){

test1();
test1();
test1();
test1();
test1();


解决方案

/ p>

  srand(time(NULL)); 

每次使用该功能。它的粒度是一秒,所以如果你在很短的时间间隔内调用它两次,你将为随机数发生器生成相同的值 - 除非时钟恰好在两次调用之间嘀嗒



您应该在程序开始时调用 srand() 一次


When I try to generate 2 random numbers from within a function call, I'm getting repeated results.

However, the rand() function works fine in loops or whatnot provided they are outside of function calls.

I'm guessing that it is because of the system time and that program is small. But I do not know how else to vary the seed.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int test1(){

    int randX, randY;
    int range = 5;

    srand( time(NULL) );

    randX = (rand() % range) + 1; 

    randY = (rand() % 15   ) + 1;
    printf("X:%d  Y:%d\n", randX, randY);
}

int main(){

    test1();
    test1();
    test1();
    test1();
    test1();
}

解决方案

It is because you call

srand( time(NULL) );

every time you use the function. Its granularity is one second, so If you call it twice within a very short time interval, you will seed the random number generator with the same value - unless the clock happens to tick just between the two calls.

You should call srand() once at the start of your program.

这篇关于rand()在多个函数调用中是一致的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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