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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM