gpt4 book ai didi

c - 在循环中生成相同的随机数序列

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

准确地说是 for 循环。我尝试使用 srand() 来播种循环,但它似乎不起作用。有人可以澄清种子部分吗?无论如何,有人可以指出我的错误吗?

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

int main(){
int a,b,c,d,loop1=0,loop2=1,count=0;
srand(1);
while(loop1!=1)
{
a=rand()%10;
b=rand()%10;
c=rand()%10;
d=rand()%10;
printf("%d %d %d %d\n",a,b,c,d);
count+=1;
if (count>3)
{
break;
}
}

return 0;
}

输出应如下所示:

1 2 3 4
1 2 3 4
1 2 3 4

最佳答案

如果您想在每次迭代中具有相同的序列,则需要在循环开始时设置种子:

while(loop1!=1) {
srand(1);
a=rand()%10;
b=rand()%10;
c=rand()%10;
d=rand()%10;
printf("%d %d %d %d\n",a,b,c,d);
count+=1;
if (count>3) {
break;
}
}

关于c - 在循环中生成相同的随机数序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529929/

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