JavaScript生成0到1之间的随机数

3
我似乎无法生成一个从0.0到1.0的随机浮点数,使用Math.floor((Math.random() * 1.0) + 0.0);。有没有解决方法?

Math.floor() 可能会将范围在 [0.0, 1.0> 内的 任何 值转换为 0.0。去掉 Math.floor() 调用。* 1.0+ 0.0 的作用是什么?只需使用普通的 Math.random() 并消除其余部分即可。 - Rudy Velthuis
也许是 Math.round(Math.random())? :) - starikovs
2个回答

10

Math.random() 方法将返回一个介于 0.01.0 之间的随机数。

示例代码:

document.getElementById("generate").onclick = function() {
  document.getElementById("random").value = Math.random();
};
<button id="generate">Generate random number</button>
<input id="random">


3
从包含0到不包含1。因此,它永远不会返回1。 - dusky
@dusky 正确。Math.random() 总是生成范围为 [0, 1) 的数字。OP 提出的最小-最大解决方案也是以同样的方式工作。 - VisioN

0

正如您所看到的,乘以1.0并加上0.0完全没有用处。破坏您机制的是Math.floor,它很可能将您的数字减少到0.0,无论Math.random返回0.0和1.0之间的任何数字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接