首页 > 语言 > JavaScript > 正文

使用Math.floor与Math.random取随机整数的方法详解

2024-05-06 15:48:05
字体:
来源:转载
供稿:网友
本篇文章对使用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的随机整数了.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选