What's wrong with my random number generator?

前端 未结 3 1670
借酒劲吻你
借酒劲吻你 2021-01-17 04:14

I\'m just diving into some C++ and I decided to make a random number generator (how random the number is, it really doesn\'t matter). Most of the code is copied off then net

相关标签:
3条回答
  • 2021-01-17 04:36

    Add srand before the loop

     srand((unsigned)time(0));
      for(int i =0;i < 100;i++)
        {
            std::cout << random_number(3,10) << endl;
        }
    
    0 讨论(0)
  • 2021-01-17 04:44

    Don't call srand() within random_number(). This will re-seed the random number generator every call. For 100 calls, you'll very likely get the same seed every call, and therefore the same number.

    0 讨论(0)
  • 2021-01-17 04:45

    The problem is that you use srand everytime. CPU is so fast that it will execute all this code in a single second, so you get the same seed each time.

    Move srand out of the loop, call it only once.

    0 讨论(0)
提交回复
热议问题