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

后端 未结 2 1012
我寻月下人不归
我寻月下人不归 2021-01-29 11:47

I\'m trying to call a class function using a loop

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


        
相关标签:
2条回答
  • 2021-01-29 12:27

    You must call srand() once, whereas you call it on every entry into generateWeight(). Since nowadays computers are fast and time() returns the time in seconds, this mostly restarts the random number generator from the same seed.

    0 讨论(0)
  • 2021-01-29 12:34

    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.

    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)

    Instead of rand() you should use std::uniform_int_distribution (requires 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';
    }
    
    0 讨论(0)
提交回复
热议问题