gpt4 book ai didi

c - 生成6个随机数时如何检查确保没有重复?

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

我可以将随机数放入数组中,但我不知道如何检查以确保它们不重复。我打印出代码,但数组中没有数字(不打印任何内容)。

//puts random numbers into an array
i = 0, j = 0;
srand(time(NULL));
for (i = 0; i < arrSize; i++)
{
randArr[i] = randNums(1,50);
}

i = 0;
for(i = 0; i < arrSize; i++)
{
printf("%d ", randArr[i]);
}

printf("\n\n");

//checks to make sure there are no duplicates
i = 0, j = 0, k = 0, temp = 0;
for (i = 0; i < arrSize; i++)
{
for (j = 1; j <= arrSize;)
{
if (randArr[j] == randArr[i])
{
for (k = j; k <= arrSize; k++)
{
temp = randNums(1,50);
randArr[k + 1] = temp;
}
arrSize--;
}
else
j++;
}
}

//generates random numbers between the inputed max and min
int randNums(int min, int max)
{
int result = 0, low = 0, high = 0;
if (min < max)
{
low = min;
high = max + 1;
}
else
{
low = max + 1;
high = min;
}
result = (rand() % (high - low)) + low;
return (result);
}

最佳答案

当心!对于这个问题有许多不同的解决方案,它们都有一个或另一个缺点。如果我要快速实现它,我会选择这样的东西(没有太多的 C 魔法):

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

#define SIZE (30)
#define RAND_MIN (1)
#define RAND_MAX (50)

static int randNums(int min, int max) {
// ...
}

int main(void) {
(void) srand(time(NULL));
int arr[SIZE];
int used = 0;
while (used < SIZE) {
int num = randNums(RAND_MIN, RAND_MAX);
bool exists = false;
for (int i = 0; i < used; ++i) {
if (arr[i] == num)
exists = true;
}
if (exists == false)
arr[used++] = num;
}
for (int i = 0; i < SIZE; ++i)
(void) printf("%d\n", arr[i]);
return EXIT_SUCCESS;
}

希望对你有一点帮助:)

关于c - 生成6个随机数时如何检查确保没有重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298935/

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