Problem in generating random number [duplicate]

女生的网名这么多〃 提交于 2019-12-02 11:24:08

问题


Possible Duplicate:
Why does it appear that my random number generator isn't random in C#?

Dear friends

I want to generate 4 random number between 1 - 55 ,but the problem is that most of the time I receive 2 number same :( for example the generated number is 2 2 5 9 or 11 11 22 22! I dont know why? I use :

Random random = new Random();
return random.Next(min, max);

for generating my random number. I put them in a While for repeating 4 times. Any Idea?Would u help me plz?


回答1:


You should create just one Random() object and reuse it instead of creating a new one for each random number you generate.

The reason is that every time you create a new Random object it seeds itself from the current time. If you create multiple Random objects within a short period of time then then they will seed with the same time, and so they will generate the same numbers.




回答2:


When you create a new Random() without specifying a seed, it seeds it using the current system time.

I don't remember off the top of my head the precision it uses (ticks? milliseconds?) but if you create new Random objects and use them in quick succession, they could easily have the same seed and thus return the same results.

Create one new Random(), and call .Next(min, max) on it repeatedly.



来源:https://stackoverflow.com/questions/3887481/problem-in-generating-random-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!