Math.floor(Math.random() * x) + 1和Math.ceil(Math.random() * x)的结果有什么不同吗?
发布于 2022-06-10 13:56:54
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 (0包含到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);
发布于 2022-06-10 13:57:36
是的,有区别。
第二个版本可能会意外地返回零,尽管这个可能性很小。
如果Math.random()本身正好返回0.0,则会发生这种情况,合法情况下是可以的。
https://stackoverflow.com/questions/72575359
复制相似问题