Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

c - Always repeated numbers given by rand()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...