new Random().Next

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);

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值