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

后端 未结 2 1041
我寻月下人不归
我寻月下人不归 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: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 
    #include 
    
    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';
    }
    

提交回复
热议问题