我似乎无法生成一个从0.0到1.0的随机浮点数,使用
Math.floor((Math.random() * 1.0) + 0.0);
。有没有解决方法?Math.floor((Math.random() * 1.0) + 0.0);
。有没有解决方法?Math.random()
方法将返回一个介于 0.0
和 1.0
之间的随机数。
示例代码:
document.getElementById("generate").onclick = function() {
document.getElementById("random").value = Math.random();
};
<button id="generate">Generate random number</button>
<input id="random">
Math.random()
总是生成范围为 [0, 1)
的数字。OP 提出的最小-最大解决方案也是以同样的方式工作。 - VisioN正如您所看到的,乘以1.0并加上0.0完全没有用处。破坏您机制的是Math.floor,它很可能将您的数字减少到0.0,无论Math.random返回0.0和1.0之间的任何数字。
Math.floor()
可能会将范围在[0.0, 1.0>
内的 任何 值转换为 0.0。去掉Math.floor()
调用。* 1.0
和+ 0.0
的作用是什么?只需使用普通的Math.random()
并消除其余部分即可。 - Rudy VelthuisMath.round(Math.random())
? :) - starikovs