js生成指定范围的随机数
因为 Math.random() 制造的随机数范围是[0, 1)想要生成16到22之间的随机数(即最小值m=16,最大值n=22),首先需要计算出最大值与最小值的差range=m-n
随后把[0, 1)这个区间的随机数乘以range,区间就拓展到[0, 6)。在此基础之上再加最小值,范围就移动到[16, 22)。就达到目的了。
// m <= x < n function randomNum(min, max) { var range = max - min; var rand = Math.random(); var randGrow = Math.floor(rand * range); //向下取整 return min+randGrow; } // m <= x <= n function randomNum(min, max) { var range = max - min; var rand = Math.random(); var randGrow = Math.round(rand * range); //四舍五入 return min+randGrow; } // m < x <= n function randomNum(min, max) { var range = max - min; var rand = Math.random(); var randGrow = Math.round(rand * range); //四舍五入 if(randGrow === 0) return min + 1; return min+randGrow; } // m < x < n function randomNum(min, max) { var range = max - min; var rand = Math.random(); var randGrow = Math.round(rand * range); //四舍五入 if(randGrow === 0) return min + 1; if(randGrow === max) return max -1; return min + randGrow - 1; }