gpt4 book ai didi

c - 使用非重复随机数(C 中)

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

我被分配创建一个非重复数字生成器,它生成 7 个数字。我已经使用了 rand 函数。但不知道如何确保数字不重复。感谢您的帮助

    int i, n;
time_t t;
n = 7;
srand((unsigned) time(&t));

for( i = 0 ; i < n ; i++ ) {
printf("%d\t", rand() % 35);}

最佳答案

您必须将之前创建的所有随机数存储到一个数组中,下次您必须将数组值与新创建的随机数进行比较,无论它是否已经创建。请参阅下面的代码并自行尝试。

int i, n;
time_t t;
n = 7;
int randval[n]
int rval = 0;
int j = 0;
srand((unsigned) time(&t));
int found = 0;
for( i = 0 ; i < n ; ) {
rval = rand();
j = 0;
found = 0;
while(j++ < i ){
if(rand[j] == rval){
found = 1;
break;
}
}
if(!found){
randval[i] = rval;
i++;
printf("%d\t", rval % 35);
}
}

关于c - 使用非重复随机数(C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47499475/

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