我必须生成一个介于0.1和1.5之间的随机数。确切的命令是什么?
const random = +(Math.random() * ((1.5- 0.1) + 0.1)).toFixed(1);
console.log(random)
发布于 2019-06-03 18:52:21
如果您想要具有0.1步长的随机数,最简单的方法是生成一个介于1和15之间的随机数,然后将结果除以10。
(Math.floor(Math.random() * 15) + 1) / 10;发布于 2019-06-03 18:54:04
Mah.random() * (max - min) + min永远是你最好的选择。如果您想稍后将其四舍五入为n小数,只需像这样包装它:Math.round(random * 10 ** n) / (10 ** n)
如果是一位小数,则为Math.round(10 * (Math.random() * (max - min) + min)) / 10
发布于 2019-06-03 18:55:02
function getRandom() {
return (Math.floor(Math.random() * 15) + 1) / 10;
}
var i = 1e6,
r,
d = {};
while (i--) {
r = getRandom();
d[r] = (d[r] || 0) + 1;
}
console.log(d);
https://stackoverflow.com/questions/56425777
复制相似问题