Always repeated numbers given by rand()

前端 未结 1 1525
终归单人心
终归单人心 2020-12-12 03:55

I use rand() in a look, and it always give me the same values several times in a row. I tried to use srand(time(NULL)) before the loop, but it does not help...

相关标签:
1条回答
  • 2020-12-12 04:26

    Usually, the only reason you get repeated numbers is if you use srand within the loop with the same seed value (and time(0) will give you the same value in a tight loop).

    Of course, a true random number sequence can give you repeated numbers. Even one that doesn't do that can give you the same number repeatedly if you're manipulating it badly.

    For example, rand() / 100000 may be a not-so-good thing to do if the algorithm tends to favour changes at the low end of the returned value since the rand() sequence of 100000, 164534, 186410, 199999 will give you 1, 1, 1, 1 (rand() % 100000 may well be a better choice in that case if changes between consecutive number is what you value).

    Of course, without seeing your actual code, guesses like that are probably the best we can do. Your best bit, as with most problem reports, is to provide a small complete sample that exhibits the problem.

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