获取随机数

  使用  RNGCryptoServiceProvider  对象  传送地址

 

  

 

     代码如下:

 /// <summary>
        /// 生成指定区间的随机数
        /// </summary>
        /// <param name="minNumber">最小值</param>
        /// <param name="maxNumber">最大值</param>
        /// <returns>输出值</returns>
        static long RangeNumber(int minNumber, int maxNumber)
        {
            //假如我想生成-10  到 100 的数
            long lResult = 0;
            byte[] bRandom = new byte[4];
            using (RNGCryptoServiceProvider randgen = new RNGCryptoServiceProvider())
            {
                randgen.GetBytes(bRandom);
                //需要判断是否两个都是负数
                if (maxNumber < 0 && minNumber < 0)
                {
                    lResult = minNumber + BitConverter.ToUInt32(bRandom, 0) % (Math.Abs(minNumber) - Math.Abs(maxNumber));
                }
                else
                {
                    lResult = minNumber + BitConverter.ToUInt32(bRandom, 0) % (maxNumber - minNumber);
                }
            }
            return lResult;
        }

 

posted @ 2020-03-11 21:31  夏风微凉  阅读(176)  评论(0编辑  收藏  举报