简体   繁体   English

rand() 即使在 srand(time(NULL)) 之后也不生成随机数

[英]rand() not generating random numbers even after srand(time(NULL))

I'm trying to call a class function using a loop我正在尝试使用循环调用类函数

for (int i = 0; i < Basket.getLemonNum(); i++)
{
    lemonWeights[i] = Fruit.generateWeight(fruit, fruitWeight);
    cout << lemonWeights[i] << " ";
}  

This goes to the Fruit class to it's member function generateWeight():这将转到 Fruit 类的成员函数 generateWeight():

   int fruitClass::generateWeight(char fruitN, int& fruitW)
    {
    srand(time(NULL));

    int weight = 0;

    switch (fruitName)
    {
    case 'a':
        weight = rand() % 500 + 100;
        return fruitW = weight;
        break;
    case 'l':
        weight = rand() % 400 + 300; 
        return fruitW = weight;
        break;
    case 'w':
        weight = rand() % 1000 + 800; 
        return fruitW = weight;
        break;
    }
} 



Output:
128 128 128 128

but it's generating the same number all the time, even when I use a different function to call it:但它一直生成相同的数字,即使我使用不同的函数来调用它:

for (int i = 0; i < Basket.getWatermelonNum(); i++)
{
    watermelonWeights[i] = Fruit.generateWeight(fruit, fruitWeight);
    cout << watermelonWeights[i] << " ";

}

Output:
128 128 128

As you can see, I did seed srand().正如你所看到的,我做了种子 srand()。 Also, the header files and are included.此外,头文件 和 也包括在内。 What is going on?到底是怎么回事?

You must call srand() once, whereas you call it on every entry into generateWeight() .您必须调用srand()一次,而在每次进入generateWeight()都调用它。 Since nowadays computers are fast and time() returns the time in seconds, this mostly restarts the random number generator from the same seed.由于现在的计算机速度很快并且time()以秒为单位返回时间,因此这主要是从同一种子重新启动随机数生成器。

The problem is that you initialize the pseudo random number generator seed again and again with the same seed (the time which has not changed since the last call since CPUs are very fast today) and, thus, you always get the same "random" number.问题是您使用相同的种子一次又一次地初始化伪随机数生成器种子(自上次调用以来的时间没有改变,因为今天 CPU 非常快),因此,您总是得到相同的“随机”数.

Generelly, 1) don't use srand() in a loop and 2) rand() has several defects as it does not generate nicely distributed random numbers (nice video about this rand() considered harmful )一般而言,1) 不要在循环中使用 srand() 和 2) rand() 有几个缺陷,因为它不能生成分布良好的随机数(关于这个rand() 的好视频被认为是有害的

Instead of rand() you should use std::uniform_int_distribution (requires C++11):您应该使用std::uniform_int_distribution而不是 rand() (需要 C++11):

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);

    for (int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM