Math.floor(Math.random() * x) + 1
的结果有区别吗和Math.ceil(Math.random() * x)
?
最佳答案
Math.random()
生成浮点值 in the interval [0, 1)(从零包含到一不包含)。这意味着两种方法之间存在细微差别:
Math.ceil(Math.random() * x)
将生成区间 [0, x] 内的整数(从零开始含 到 x
包含)。这是因为 Math.ceil(0)
将返回零。虽然获得的几率极小。
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.ceil(minRandom() * x));
console.log("max:", Math.ceil(maxRandom() * x));
Math.floor(Math.random() * x) + 1
将生成区间 [1, x] 内的整数(从一个包含 到 x
包含)。这是因为 Math.floor(Math.random() * x)
本身会生成区间 [0, x-1] 内的整数(包括零 到 x-1
包含)。
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.floor(minRandom() * x) + 1);
console.log("max:", Math.floor(maxRandom() * x) + 1);
关于JavaScript - 随机函数结果之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72575359/