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

前端 未结 5 1955
清酒与你
清酒与你 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 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.

提交回复
热议问题