乐闻世界logo
搜索文章和话题

如何在 javascrip 中生成随机整数

7 个月前提问
3 个月前修改
浏览次数40

6个答案

1
2
3
4
5
6

在 JavaScript 中,要生成指定范围内的随机整数,你可以使用 Math.random() 函数来获得一个 [0, 1) 区间内的随机浮点数,然后通过适当的计算将其转换为你需要范围内的整数。

以下是一个如何生成介于 minmax 之间的随机整数(包括 minmax)的函数示例:

javascript
function getRandomIntInclusive(min, max) { min = Math.ceil(min); // 确保最小值是整数 max = Math.floor(max); // 确保最大值是整数 return Math.floor(Math.random() * (max - min + 1)) + min; // 向下取整以确保结果为整数 }

使用这个函数,你可以通过传入不同的 minmax 来得到一个在这个范围内的随机整数。例如:

javascript
let randomNum = getRandomIntInclusive(1, 10); // 生成一个1到10之间的随机整数,包括1和10 console.log(randomNum);

这段代码会在控制台打印出一个介于 1 到 10 之间的随机整数。

2024年6月29日 12:07 回复

Mozilla 开发者网络页面上有一些示例:

shell
/** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn't an integer) and no greater than max (or the next integer * lower than max if max isn't an integer). * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }

这是其背后的逻辑。这是一个简单的三条规则:

Math.random()返回Number介于 0(包含)和 1(不包含)之间的值。所以我们有一个这样的区间:

shell
[0 .................................... 1)

现在,我们想要一个min介于(包含)和max(不包含)之间的数字:

shell
[0 .................................... 1) [min .................................. max)

我们可以使用 来Math.random获取 [min, max) 区间内的对应项。但是,首先我们应该通过min从第二个区间中减去一点来解决这个问题:

shell
[0 .................................... 1) [min - min ............................ max - min)

这给出:

shell
[0 .................................... 1) [0 .................................... max - min)

我们现在可以申请Math.random然后计算对应的。让我们选择一个随机数:

shell
Math.random() | [0 .................................... 1) [0 .................................... max - min) | x (what we need)

因此,为了找到x,我们会这样做:

shell
x = Math.random() * (max - min);

不要忘记加min回来,这样我们就得到了 [min, max) 区间内的数字:

shell
x = Math.random() * (max - min) + min;

这是 MDN 的第一个功能。第二个返回介于min和之间的整数max(包含两者)。

现在要获取整数,您可以使用round,ceilfloor

您可以使用Math.round(Math.random() * (max - min)) + min,但这会产生不均匀的分布。两者都有,min并且max只有大约一半的机会滚动:

shell
min...min+0.5...min+1...min+1.5 ... max-0.5....max └───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round() min min+1 max

如果将max其排除在间隔之外,则滚动的机会甚至比 还要小min

这样Math.floor(Math.random() * (max - min +1)) + min你就有了一个完美均匀的分布。

shell
min... min+1... ... max-1... max.... (max+1 is excluded from interval) └───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor() min min+1 max-1 max

您不能在该等式中使用ceil()and ,因为现在滚动的机会稍少,但您也可以滚动(不需要的)结果。-1``max``min-1

2024年6月29日 12:07 回复

var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

2024年6月29日 12:07 回复

数学.随机()

返回min(包含)和 max(包含)之间的整数随机数

shell
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }

或者min(包含)和 max(不包含)之间的任何随机数:

shell
function randomNumber(min, max) { return Math.random() * (max - min) + min; }

有用的示例(整数):

shell
// 0 -> 10 const rand1 = Math.floor(Math.random() * 11); // 1 -> 10 const rand2 = Math.floor(Math.random() * 10) + 1; // 5 -> 20 const rand3 = Math.floor(Math.random() * 16) + 5; // -10 -> (-2) const rand4 = Math.floor(Math.random() * 9) - 10; console.log(rand1); console.log(rand2); console.log(rand3); console.log(rand4);

运行代码片段Hide results

展开片段

** 总是很高兴被提醒(Mozilla):

Math.random() 不提供加密安全随机数。请勿将它们用于与安全相关的任何事情。请改用 Web Crypto API,更准确地说是 window.crypto.getRandomValues() 方法。

2024年6月29日 12:07 回复

使用:

shell
function getRandomizer(bottom, top) { return function() { return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom; } }

用法:

shell
var rollDie = getRandomizer( 1, 6 ); var results = "" for ( var i = 0; i<1000; i++ ) { results += rollDie() + " "; // Make a string filled with 1000 random numbers in the range 1-6. }

分解:

我们返回一个函数(借用函数式编程),当调用该函数时,将返回值bottom和之间的随机整数top(含)。我们说“包含”是因为我们希望将底部和顶部都包含在可返回的数字范围内。这样,getRandomizer( 1, 6 )将返回 1、2、3、4、5 或 6。

(“底部”是较小的数字,“顶部”是较大的数字)

shell
Math.random() * ( 1 + top - bottom )

Math.random()``top返回 0 和 1 之间的随机双精度值,如果我们将其乘以 1 加上和之间的差值,我们将得到和bottom之间的双精度值。0``1+b-a

shell
Math.floor( Math.random() * ( 1 + top - bottom ) )

Math.floor将数字向下舍入到最接近的整数。现在我们有了0和之间的所有整数top-bottom。 1 看起来令人困惑,但它必须存在,因为我们总是向下舍入,因此如果没有它,实际上永远不会达到最高数字。我们生成的随机小数需要在0to范围内,以便我们可以向下舍入并获得在to(1+top-bottom)范围内的整数:0``top-bottom

shell
Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom

前面示例中的代码为我们提供了0和范围内的整数top-bottom,因此我们现在需要做的就是与该结果相加,以获得范围和范围内的bottom整数。 :Dbottom``top


注意:如果您首先传入非整数值或更大的数字,您将得到不良行为,但除非有人请求,否则我不会深入研究参数检查代码,因为它与原始问题的意图相去甚远。

2024年6月29日 12:07 回复

所有这些解决方案都使用了太多的火力。你只需要调用一个函数:Math.random();

shell
Math.random() * max | 0;

这将返回 0(包含)和 max(不包含)之间的随机整数。

2024年6月29日 12:07 回复

你的答案