Math.floor( Math.random() )生成随机整数

Math.random():获取0~1随机数
Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (小于等于 x,且与 x 最接近的整数。)
其实返回值就是该数的整数位:
Math.floor(0.666) --> 0
Math.floor(39.2783) --> 39

所以我们可以使用Math.floor(Math.random())去获取你想要的一个范围内的整数。
如:现在要从1~52内取一个随机数:
首先Math.random()*52 //这样我们就能得到一个 >=0 且 <52的数
然后加1:Math.random()*52 + 1 //现在这个数就 >=1 且 <53
再使用Math.floor取整

最终: Math.floor(Math.random()*52 + 1)
这就能得到一个取值范围为1~52的随机整数了.


Math.(random/round/cell/floor)随机数的用法

Math.random() 返回值是一个大于等于0,且小于1的随机数

Math.random()*N 返回值是一个大于等于0,且小于N的随机数

Math.round() 四舍五入的取整
Math.ceil() 向上取整,如Math.cell(0.3)=1 、又如Math.ceil(Math.random()*10) 返回1~10
Math.floor() 向下取整,如Math.floor(0.3)=0、又如Math.floor(Math.random()*10)返回0~9

引申:
Math.round(Math.random()*15)+5; 返回5~20随机数

Math.round(Math.random()*(y-x))+x; 返回x~y的随机数,包换负数。

非常感谢 转自:https://blog.csdn.net/hsany330/article/details/40786493

  • 22
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值