封装函数,返回x~y之间的随机整数

function fn(x, y) {
    return Math.floor(Math.random() * (y - x + 1)) + x
}
console.log(fn(10, 20));

要生成x~y之间的随机整数,我们需要以下两个步骤:

  1. 生成介于0和1之间的随机小数。

在JavaScript中,Math.random()方法返回一个大于等于0且小于1的浮点数。

console.log(Math.random());//0到0.9999...之间的随机数
  1. 将随机小数转换成介于x和y之间的随机整数。

假设我们要求的范围是1~10之间的整数

Math.floor的作用是向下取整

console.log(Math.floor(Math.random()*10));
//那么我们在Math.random后面乘以10,就可以得出0到10之间的整数(不包含10),即0~9

由于我们需要的是1~10之间的整数,不是0~10(不包含10)之间的整数

因此我们要是结果为(1+0)~(1+9),即1~10之间的整数

0~10的时候 Math.random()*11
0~20的时候 Math.random()*21
0~30的时候 Math.random()*31
0~x 的时候 Math.random()*(x+1)
即console.log(Math.floor(Math.random()*(10+1)));
返回x~y之间的随机数
 0~10的时候,返回 (0~10)+0
10~20的时候,返回 (0~10)+10
20~30的时候,返回 (0~20)+20
10~30的时候,返回 (0~20)+10
 x~y 的时候,返回 (0~y-x)+x
即console.log(Math.floor(Math.random() * (y - x + 1)+x));

那么完整的代码:

function fn(x, y) {
    return Math.floor(Math.random() * (y - x + 1)) + x
}
console.log(fn(10, 20));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值