//這樣產生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);