C# 生成设置范围内的Double的随机数

/// <summary>
        /// 生成设置范围内的Double的随机数
        /// eg:_random.NextDouble(1.5, 2.5)
        /// </summary>
        /// <param name="random">Random</param>
        /// <param name="miniDouble">生成随机数的最大值</param>
        /// <param name="maxiDouble">生成随机数的最小值</param>
        /// <returns>当Random等于NULL的时候返回0;</returns>
        protected static double NextDouble(Random random, double miniDouble, double maxiDouble)
        {

            double num = maxiDouble - miniDouble;
            if (num <= double.MaxValue)
            {
                var ran = random.NextDouble();
                var numRes = (ran * (double)num) + miniDouble;
                return numRes;
            }


            int RandNum = random.Next();

            if ((random.Next() % 2 == 0) ? true : false)
            {
                num = -num;
            }

            double num2 = num;
            num2 += 2147483646.0;
            num2 = num2 / 4294967293.0;


            return (num2 * (double)num) + miniDouble;

        }

posted @ 2021-05-11 15:48  LuoCore  阅读(1464)  评论(0编辑  收藏  举报