【问题标题】:rand() numbers addicted in function in C [duplicate]rand()数字沉迷于C中的函数[重复]
【发布时间】:2016-11-04 00:29:34
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int dorand(){
int i;
srand(time(0));
i = rand()%3+1;
return i;
}

int main (){
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}

问题是:四个 printf 正在打印相同的数字。 当我直接在主函数中执行 rand() 时,根本没有问题,但是当我调用一个函数时,随机生成会沉迷于相同的数字。有人有经验分享一下吗?

我试过了:

int main (){
srand(time(0)) //seeding in the main function before calling the dorand function
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}

还有

int dorand(){
int i;
i = 0; //clearing the variable before attributing a new rand value
srand(time(0));
i = rand()%3+1;
return i;
}

对不起,如果我弄错了什么,感谢您的帮助

【问题讨论】:

  • 你一直在重置种子。
  • 尽量不要每次函数调用都改变种子。尝试仅在 main(或其他地方)调用此 srand(time(0)); 一次。
  • 工作,非常感谢大家
  • 很高兴我们能提供帮助。如果您觉得有用,请随时 accept an answer。

标签: c function random


【解决方案1】:

srand 函数为随机数生成器提供种子。对于给定的种子值,会生成相同的随机数集。

由于您每次需要一个随机数时都重新播种,使用当前时间作为种子,假设每次调用函数发生在同一秒内,随机数函数被播种为相同的值,所以您不断得到相同的“随机”数字。

您应该在程序开始时只调用一次srand。把dorand的调用去掉,放到main的顶部。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2014-11-05
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多