gpt4 book ai didi

c - srand(time(nul)) 无法正常工作

转载 作者:行者123 更新时间:2023-11-30 17:14:52 25 4
gpt4 key购买 nike

我有一个使用 srand(time(null)) 的函数,它运行良好,在每次迭代时生成不同的数字。然后,我在函数中添加了一段时间,现在它在循环的每次迭代期间生成相同的两个数字。这是我的代码:

void readgraph()
{
int i,vi=0,vj=0;
for(i=0; i<nrVertices; i++)
G[i]=NULL;

for(i=0; i<nrVertices; i++)
{
srand(time(NULL));
while(checkInsert(vi,vj)==false) //this is the while that I added
{

vi=rand()%nrVertices;
vj=rand()%nrVertices;
while(vj==vi)
{
vj=rand()%nrVertices;
}
}
printf("%d %d\n",vi,vj);
insert(vi,vj);
insert(vj,vi);
}
}

知道如何解决这个问题吗?谢谢。

@milleniumbug 我的“短可编译代码”:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define MAX 10000
#include <sys/time.h>

typedef struct node
{
struct node *next;
int vertex;
} node;
int a[10000][10000];
int nrVertices=100;
int nrEdges=1000;
node *G[10000]; //heads of the linked list
void readgraph()
{
int i,vi=0,vj=0;
for(i=0; i<nrVertices; i++)
G[i]=NULL;
for(i=0; i<nrEdges; i++)
{
while(checkInsert(vi,vj)==false)
{

vi=(rand()+i-2)%nrVertices;
vj=(rand()+i+7)%nrVertices;
while(vj==vi)
{
vj=rand()%nrVertices;
}
}
printf("%d %d\n",vi,vj);
//insert(vi,vj);
//insert(vj,vi);
}
}
int main()
{
srand(time(NULL));
readgraph();
return 0;
}

最佳答案

您应该运行srand一次 - 否则您每次都会重新初始化状态,这给您使用了time(NULL),生成的数字仅每秒发生变化,并且完全可预测。

关于c - srand(time(nul)) 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151736/

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