javascript生成随机数的问题
ringa_lee
ringa_lee 2017-04-11 12:12:18
[JavaScript讨论组]

W3C上有一个教程代码生成1-3的随机数是这样的

slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;

(3 -1 + 1)这个是为什么?就我所知道的,要生成0-n的随机数

Math.floor(Math.random() * n);

所以既然是1-3,应该是

Math.floor(Math.random() * 3) + 1;

希望有大神解释一下...
是网站人员的问题,还是有其他的原因...

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
怪我咯

生成一个m~n的随机数,则最小值为m+0,最大值为m+(n-m+1);
Math.random()生成的是0~1,故Math.floor(Math.random() * (n - m + 1)) + m 套入1-3就是你要的值

天蓬老师
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}



//公式Math.floor(Math.random() * (max - min + 1) + min)
//因为Math.floor是向下取整,虽然Math.random() * (max - min) + min 生成min-max之间的随机数
//但因为Math.floor的关系,取整后最大值是max-1;所以需要+1
//最小值不管怎么取整都肯定是min
//套入公式就是(3+1-1);这里的关键不是3+1-1=3,而是公式,比如2-4的话4—2+1肯定不等于4吧
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号