如何用JavaScript生成指定范围内总和为固定值的多个随机数
解决方案
核心思路
- 先确认需求可行性:12个数字最小值总和为
12*6.0=72,最大值总和为12*9.99=119.88,目标总和88.3在合理区间内,可实现。 - 为避免JS浮点数精度误差,将所有数值放大100倍转为整数计算:目标总和转为8830,单个数字取值范围转为600~999。
- 初始给12个数字都赋最小值600,此时已用总和为7200,剩余待分配额度为
8830-7200=1630。 - 循环将剩余额度逐份分配给随机位置的数字,直到额度耗尽,每次分配时保证单个数字不超过上限999。
- 最终将所有数字除以100转回两位小数的数值即可。
完整可运行代码
// 复用你已有的随机整数生成方法 function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function generateTargetNumbers(total, count, minVal, maxVal) { // 放大100倍转整数避免精度问题 const MULTIPLE = 100; const intTotal = Math.round(total * MULTIPLE); const intMin = Math.round(minVal * MULTIPLE); const intMax = Math.round(maxVal * MULTIPLE); // 初始化所有数值为最小值 const nums = new Array(count).fill(intMin); let remaining = intTotal - count * intMin; // 分配剩余额度 while (remaining > 0) { // 随机选一个位置 const randomIndex = getRandomInt(0, count - 1); // 该位置还能加的最大值 const canAdd = intMax - nums[randomIndex]; if (canAdd <= 0) continue; // 已经到上限就跳过 // 每次最多加1,或者把剩余的都加完 const add = Math.min(1, remaining); nums[randomIndex] += add; remaining -= add; } // 转回正常数值,保留两位小数 return nums.map(num => Number((num / MULTIPLE).toFixed(2))); } // 调用测试:总和88.3,12个数字,范围6.0~9.99 const result = generateTargetNumbers(88.3, 12, 6.0, 9.99); console.log('生成的12个随机数:', result); console.log('总和验证:', result.reduce((sum, cur) => sum + cur, 0).toFixed(1));
效果验证
运行代码后控制台会输出生成的12个数字,以及总和校验结果,你可以多次运行测试,每次生成的数字都是随机的,且都满足范围要求、总和恰好为88.3。
内容的提问来源于stack exchange,提问作者Marco Almeida
相关产品推荐
相关产品推荐

