//这样产生0 ~ 100的强随机数(含100)
int max = 100;int rnd = int.MinValue;decimal _base = (decimal)long.MaxValue;byte[] rndSeries = new byte[8];System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();rng.GetBytes(rndSeries);//不含100需去掉+1 rnd = (int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * (max+1));//这个rnd就是你要的随机数,//但是要注意别扔到循环里去,实例化RNG对象可是很消耗资源的原文地址:http://www.2cto.com/kf/201007/52493.html
/// <summary>
/// 生成随机数 /// </summary> /// <param name="minVal">最小值(包含)</param> /// <param name="maxVal">最大值(不包含)</param> /// <returns></returns> public static int GetRandom(int minVal, int maxVal) { //这样产生0 ~ 100的强随机数(不含100) int m = maxVal - minVal; int rnd = int.MinValue; decimal _base = (decimal)long.MaxValue; byte[] rndSeries = new byte[8]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(rndSeries); long l = BitConverter.ToInt64(rndSeries, 0); rnd = (int)(Math.Abs(l) / _base * m); return minVal + rnd; }使用:
int randomi = 0;
randomi = GetRandom(100000, 999999);