Calling a random number generating member function doesn't produce entirely random numbers

前端 未结 1 1819
梦毁少年i
梦毁少年i 2020-12-20 20:15

I\'m creating a wxWidget application with C++ where at the start of the program I want the application window to contain pixels with random colors like this:

相关标签:
1条回答
  • 2020-12-20 20:54

    The issue here is that you constantly recreate and seed the random number generator in rand_node_colour. You call it in a tight loop so you can get the same time which means the seed will be the same and that means the random numbers generated will be the same.

    What you need to do is seed the generator once and then keep using its random output. An easy way to fix you code would be to make it static in the function sos it is only initialized once and each subsequent call to the function will continue on instead of start the generator all over. If we do that the code becomes

    void rand_node_colour(int nodeWeights[])
    {
      // construct a trivial random generator engine from a time-based seed:
      static std::default_random_engine generator (std::chrono::system_clock::now().time_since_epoch().count());
      std::uniform_int_distribution<int> distribution(0,255);
      for(int i=0; i<3; i++)
      {
        nodeWeights[i] = distribution(generator);
      }
    }
    
    0 讨论(0)
提交回复
热议问题