rand() returns same values when called within a single function

前端 未结 5 1912
清酒与你
清酒与你 2020-11-22 15:25

I\'m a C++ newbie and I\'m stumped on this. I need to call this function in my main function three times but each time it gives me the same result, i.e. pull_1, pull_2, pul

相关标签:
5条回答
  • 2020-11-22 15:59

    Your problem is that you seed the RNG each time you call the function. You should only seed this once in a program for best results. If you want the result to vary from one execution of the program to the next, srand based on the result of the time() function.

    0 讨论(0)
  • 2020-11-22 16:07

    The random number generator is reset to an initial state, which is dictated by the seed value, every time you call srand. Time value may be the same between successive calls to time, hence the same seed and the same number generated.

    Call seeding function (srand) only once in your main function before generating random samples.

    0 讨论(0)
  • 2020-11-22 16:15

    You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.

    The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.

    0 讨论(0)
  • 2020-11-22 16:20

    The time(0) function may not have 'ticked' between function calls. So you are seeding the random number generator with the same value each time, leading to identical values for rand()

    0 讨论(0)
  • 2020-11-22 16:22

    Why do you keep calling std::srand(time(0));? That re-seeds the PRNG.... and because this all happens within the same second, you're always re-seeding it with the same sequence.

    Call srand once in your program, and once only.

    Also, I would recommend, at least on POSIX-compliant systems, something like std::srand(time(0) ^ getpid()), so that you can run your program twice within the same "second" and still get a new PRNG sequence.

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