【发布时间】:2021-11-12 13:48:58
【问题描述】:
我是 javascript 新手,不知道如何解决这个问题。我有一个 88.3 的固定值,我需要 6.0 到 9.99 之间的 12 个随机数,当我将它们全部相加时,它们匹配 88.3。
到目前为止,我设法使用此代码在一个范围内生成随机数:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
谁能帮帮我?
【问题讨论】:
-
方法错误,你要计算你与目标值的偏差
-
@aerial301 感谢您的链接,但它没有回答。例如,如果我将最大值设置为 88.3,它会返回第一个随机数 75,然后返回所有其他随机数 1。这不是我需要的。
-
@MarcoAlmeida 您首先必须调整
randombetween函数以检查生成的随机值是否在所需范围之间。如果没有,则生成一个新的。另外,删除Math.floor,因为你不想要只整数。
标签: javascript random