gpt4 book ai didi

c - 在带链表的递归函数中使用 rand()

转载 作者:行者123 更新时间:2023-11-30 18:49:43 24 4
gpt4 key购买 nike

当我运行代码时,rand()函数似乎生成相同的非随机数(我的目的是在 value 中生成随机数)。如果代替rand()我使用形式参数length ,代码似乎有效(数量减少)。我哪里做错了?

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

struct node{
int value;
struct node *next;
};

struct node *construct(int);

int main(){
struct node *list = construct( 5 );

while( list ){
printf(" %i\n", list->value);
list = list->next;
}

return 0;
}

//It builds a list of "length" items recursively
struct node *construct(int length){
struct node *node = (struct node *) malloc(sizeof(struct node));

srand(time(NULL));

node->value = rand(); /* unclear part of code */

if( length - 1){
node->next = construct( length - 1 );
}

return node;
}
/* missing the code to free memory */

/* example of output */
837240329
837240329
837240329
837240329
837240329

最佳答案

srand() 函数采用种子并初始化伪随机数字生成器。

伪随机数生成器不是随机的。相反,它生成由种子确定的非常固定的数字序列。不同的种子会产生不同的序列,但相同的种子,即使多年后,也会产生相同的序列。 (这是一个功能 - 它可以让您调试行为“随机”的程序。)

就您而言,每次调用 construct 函数时,您都会为随机数生成器播种。这是错误的。您应该在 main() 函数中播种一次 RNG。

就目前情况而言,您的构造函数将运行得很快。您的种子基于 time()。因此,您很可能一次又一次地获得相同的结果,因为您的函数完成得如此之快。

(有点像当你坐在 session 中等待 session 结束时,你不断地查看时钟 - 而且时间总是相同的......)

无论如何,您调用 srand(X)(无论 X 是什么),然后在很少的指令之后再次调用 srand(X)。因此,您将获得相同的随机数序列并且仅使用第一个!

如果你从main调用srand(),那就没问题了。如果您根本没有调用 srand() 那就没问题了。但事实上,你总是会得到srand(X)[0] 作为构造函数中的随机数。

关于c - 在带链表的递归函数中使用 rand(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com