Always repeated numbers given by rand()

2020-02-07 06:19发布

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...

标签: c random
1条回答
爷的心禁止访问
2楼-- · 2020-02-07 06:51

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.

查看更多
登录 后发表回答