' 按权重比例生成随机数 Private Function GenerateNumbersByWeight(targetValue As Double, weights() As Double, isInteger As Boolean) As Double() Dim count As Integer = weights.Length Dim numbers(count - 1) As Double ' 为每个权重添加少量随机波动(可选) For i As Integer = 0 To count - 1 ' 基础值按权重计算 Dim baseValue As Double = targetValue * weights(i) ' 添加 ±10% 的随机波动 Dim fluctuation As Double = baseValue * 0.1 * (random.NextDouble() * 2 - 1) Dim randomValue As Double = baseValue + fluctuation If isInteger Then numbers(i) = Math.Round(randomValue) Else numbers(i) = Math.Round(randomValue, 2) End If Next ' 调整第一个数确保总和等于目标值 Dim actualSum As Double = numbers.Sum() Dim adjustment As Double = targetValue - actualSum If isInteger Then numbers(0) = Math.Round(numbers(0) + adjustment) Else numbers(0) = Math.Round(numbers(0) + adjustment, 2) End If Return numbers End Function

' ================================================================ ' 模式一:几个和=原数 ' 使用"前瞻法":每次生成时预留后续数的空间,确保最后一个数合法 ' ================================================================ Private Function GenerateBySum(targetValue As Double, splitCount As Integer, minVal As Double, maxVal As Double, isInteger As Boolean) As Double() Dim numbers(splitCount - 1) As Double Dim sumSoFar As Double = 0 Dim remainingCount As Integer = splitCount For i As Integer = 0 To splitCount - 1 remainingCount -= 1 ' 剩余数至少需要的最小总和 Dim needMin As Double = remainingCount * minVal ' 剩余数至多能接受的最大总和 Dim needMax As Double = remainingCount * maxVal ' 当前数可取范围 Dim low As Double = Math.Max(minVal, targetValue - sumSoFar - needMax) Dim high As Double = Math.Min(maxVal, targetValue - sumSoFar - needMin) If low > high Then ' 约束冲突,取中点逼近 low = minVal high = maxVal End If If isInteger Then low = Math.Ceiling(low) high = Math.Floor(high) If low > high Then low = high numbers(i) = Math.Round(low + random.NextDouble() * (high - low)) Else numbers(i) = Math.Round(low + random.NextDouble() * (high - low), 2) End If sumSoFar += numbers(i) Next Return numbers End Function