# 2个双数之间的随机数

``public double GetRandomeNumber(double minimum, double maximum) { return Random.NextDouble(minimum, maximum) }` `

` `double result = GetRandomNumber(1.23, 5.34);` `

Random.NextDouble返回一个介于0和1之间的双精度值。然后将其乘以所需的范围（最大值和最小值之间的差值），然后将其加到基值（最小值）。

` `public double GetRandomNumber(double minimum, double maximum) { Random random = new Random(); return random.NextDouble() * (maximum - minimum) + minimum; }` `

Johnny5build议创build一个扩展方法。 下面是一个更完整的代码示例，展示如何做到这一点：

` `public static class RandomExtensions { public static double NextDouble( this Random random, double minValue, double maxValue) { return random.NextDouble() * (maxValue - minValue) + minValue; } }` `

` `Random random = new Random(); double value = random.NextDouble(1.23, 5.34);` `

` `var random = new Random(); for(int d = 0; d < 7; d++) { // Actual BOE boes.Add(new LogBOEViewModel() { LogDate = criteriaDate, BOEActual = GetRandomDouble(random, 100, 1000), BOEForecast = GetRandomDouble(random, 100, 1000) }); } double GetRandomDouble(Random random, double min, double max) { return min + (random.NextDouble() * (max - min)); }` `

` `public double getRandomNumber(double minimum, double maximum) { return minimum + randomizer.nextDouble() * (maximum - minimum); }` `

` `public class RandomNumbers : Random { public RandomNumbers(int seed) : base(seed) { } public double NextDouble(double minimum, double maximum) { return base.NextDouble() * (maximum - minimum) + minimum; } }` `

` `double NextDouble(double min, double max) { if (min >= max) throw new ArgumentOutOfRangeException(); return random.NextDouble() * (Math.Abs(max-min)) + min; }` `

“为什么？”你问。

` `Random random = new Random(); double NextDouble(double minimum, double maximum) { return random.NextDouble()*random.Next(minimum,maximum); }` `

` `// Because of: double.MaxValue - double.MinValue == double.PositiveInfinity // This will be equals to NaN or PositiveInfinity random.NextDouble() * (double.MaxValue - double.MinValue)` `

` `public static class RandomExtensions { public static double NextDoubleInMinMaxRange(this Random random) { var bytes = new byte[sizeof(double)]; var value = default(double); while (true) { random.NextBytes(bytes); value = BitConverter.ToDouble(bytes, 0); if (!double.IsNaN(value) && !double.IsInfinity(value)) return value; } } }` `