赞
踩
在C#编程的时候,经常会遇到需要用到随机数,而如果只是简单调用 Random,所产生的实际不是随机数,当调用过快,或者程序连续调用时,通常产生“固定”的数。经过摸索与测试,我一般会自己写一个函数,可以保证在任何一次调用,都最大概率产生真正的随机数,代码如下,可以直接使用哦:
private int GetRandomInAB(int minA, int maxB) //在A到B的区间随机取值返回,如果B小于等于A,或溢出,返回-1
{
int iRandomBack = -1; //防溢出,固定回传
if (maxB > minA) //B大于A
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); //采用 RNGCryptoServiceProvider取随机数
rng.GetBytes(bytes);
int Randseed = BitConverter.ToInt32(bytes, 0); //产生一个随机种子
string strTick = Convert.ToString(DateTime.Now.Ticks); //采用DateTime.Now.Ticks取随机数
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。