js 取任意两个数之间的随机整数

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}

上面的例子是取[min, max)左闭右开区间的任意数字,假如取[0, 100)之间的随机数,是取不到100的。Math.random() => 取[0, 1)之间的任意随机数字。

怎么处理才能取到100呢?也就是怎么变成闭区间呢?

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //不含最大值,含最小值
}
以min = 0, max = 100,为例:
Math.random() * (100 - 0 + 1) => [0, 101)
Math.floor([0, 101)) => 0,1,2,...,100
Math.floor([0, 101)) + 0 => 0,1,2,...,100
posted @ 2019-04-08 20:28  whq920729  阅读(2392)  评论(0编辑  收藏  举报