c - 为什么随机数生成器不断重复相同的数字?

标签 c random numbers

<分区>

这个程序的目标是将 6 个随机数添加到一个 1 到 50 之间的数组中,并且不能有任何重复。我主要在检查以确保没有任何重复时遇到问题。

我尝试了很多东西,但我似乎无法弄明白。 (在此之前还有更多代码与我的问题无关)。

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


            //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);
                                            temp = randArr[k];
                                            randArr[k] = randArr[k + 1];
                                            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;
       }

       srand(time(NULL));
       result = (rand() % (high - low)) + low;

       return (result);
}

最佳答案

几个观察结果:

  1. 您需要调用 srand()(您正在执行)

  2. 您应该只调用 srand() 一次(您调用了多次)

  3. rand() 返回的值可以重复。你需要考虑到这一点。

  4. 请记住,C 库使用“伪随机”算法 - 它不是真正的“随机”。

另请看这里:

https://www.gnu.org/software/libc/manual/html_node/Pseudo_002dRandom-Numbers.html#Pseudo_002dRandom-Numbers

The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.

...

You can obtain repeatable sequences of numbers on a particular machine type by specifying the same initial seed value for the random number generator. There is no standard meaning for a particular seed value; the same seed, used in different C libraries or on different CPU types, will give you different random numbers.

关于c - 为什么随机数生成器不断重复相同的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281795/

相关文章:

javascript - 按钮中的随机数会自行迭代!我怎样才能从迭代中删除它?

c - 查找给定整数的所有精确除数的算法

c++ - 使用后缀表示法在 C++ 中输入数字

c - 如何用另一个函数覆盖一个函数?

c - 延迟写入错误

c++ - SQLite 总是回复 "database table is locked"

java - 存储 20 位数字的数据类型

objective-c - 段错误 11 Objective-C,但 C 中没有

google-app-engine - 为什么我的随机数没有更新?

java - 随机列表处理比 Collections.shuffle() 更快?