[C#/.NET]C#/.NET应用程序编程开发中如何实现生成指定范围内的随机小数(浮点数)呢?
2.1K 次浏览
2 个回答
-
创建一个生成随机小数的静态扩展方法,如下:
public static decimal NextDecimal(this Random rnd, decimal from, decimal to) { byte fromScale = new System.Data.SqlTypes.SqlDecimal(from).Scale; byte toScale = new System.Data.SqlTypes.SqlDecimal(to).Scale; byte scale = (byte)(fromScale + toScale); if (scale > 28) scale = 28; decimal r = new decimal(rnd.Next(), rnd.Next(), rnd.Next(), false, scale); if (Math.Sign(from) == Math.Sign(to) || from == 0 || to == 0) return decimal.Remainder(r, to - from) + from; bool getFromNegativeRange = (double)from + rnd.NextDouble() * ((double)to - (double)from) < 0; return getFromNegativeRange ? decimal.Remainder(r, -from) + from : decimal.Remainder(r, to); }
调用示例:
var rnd = new Random(); var result = rnd.NextDecimal(1.0M, 9999.0M);
输出结果:9863.58
-
另外一个生成随机小数的静态扩展方法,如下:
public static class RandomExtension { public static decimal NextDecimal1(this Random rnd, decimal from, decimal to) { var fromScale = new System.Data.SqlTypes.SqlDecimal(from).Scale; var toScale = new System.Data.SqlTypes.SqlDecimal(to).Scale; var scale = (byte)(fromScale + toScale); if (scale > 28) scale = 28; var r = new decimal(rnd.Next(), rnd.Next(), rnd.Next(), false, scale); if (Math.Sign(from) == Math.Sign(to) || from == 0 || to == 0) return decimal.Remainder(r, to - from) + from; var getFromNegativeRange = (double)from + rnd.NextDouble() * ((double)to - (double)from) < 0; return getFromNegativeRange ? decimal.Remainder(r, -from) + from : decimal.Remainder(r, to); } public static int NextInt32(this Random rng) { var firstBits = rng.Next(0, 1 << 4) << 28; var lastBits = rng.Next(0, 1 << 28); return firstBits | lastBits; } public static decimal NextDecimalSample(this Random random) { var sample = 1m; while (sample >= 1) { var a = random.NextInt32(); var b = random.NextInt32(); var c = random.Next(542101087); sample = new decimal(a, b, c, false, 28); } return sample; } public static decimal NextDecimal(this Random random) { return NextDecimal(random, decimal.MaxValue); } public static decimal NextDecimal(this Random random, decimal maxValue) { return NextDecimal(random, decimal.Zero, maxValue); } public static decimal NextDecimal(this Random random, decimal minValue, decimal maxValue, int places = 2) { var nextDecimalSample = NextDecimalSample(random); return decimal.Round(maxValue * nextDecimalSample + minValue * (1 - nextDecimalSample), places); } }