new Random().Next

来源:互联网 发布:淘宝回收移动充值卡 编辑:程序博客网 时间:2024/05/17 23:28

Random.Next 生成一个值范围在零与Int32.MaxValue 之间的随机数。若要生成值范围在零与其他某个正数之间的随机数,请使用Random.Next(Int32) 方法重载。若要生成在不同范围内的随机数,请使用Random.Next(Int32, Int32) 方法重载。

Random() doesn't always work the best. There are two things I do in order to make it work better.

1. Seed random with something, I like to use DateTime.Now.Millisecond. So when I create a new instance, I do something like this: randomNumber = new Random(DateTime.Now.Millisecond);

2. Create one instance of your random number and use it each time you need a random number. Often if you have multiple random number instances and call them in the same iteration through your code, you'll end up getting the same number from each.

Good luck, hope this helps.

 

但Random.Next()工作并不是很好,经常容易获得相同的随机数。为保证每次获得的随机数不同,可以考虑:增大两次间随机间隔 Sleep(1000), 或者delay一下。或者采用时间点的种子。可以考虑采用一下2种方法:

(1)产生一颗随机种子。可以使用DateTime.Now.Millisecond。

我测试了采用DateTime.Now.Millisecond方法作为种子,产生相同数字的概率很大;甚至让线程sleep  5000,都没能解决。所以采用了下面的方法。

(2)采用guide作为种子,这样可以避免相同的数字产生。
                Random rand = new Random(Guid.NewGuid().GetHashCode());                int aa = rand.Next(0, 99);

原创粉丝点击