【学习笔记】使用Math.floor与Math.random取随机整数的方法详解
2015-10-08 13:24
429 查看
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.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的随机整数了.
相关文章推荐
- 卡夫卡(kafka)
- Struts2 Setter&Getter
- JDK源码解析之ThreadLocal类
- ubuntu不能设置高分辨率问题的解决方法
- 批量读取图片中关于缺失dirent.h的问题
- linux上安装nginx简单几步
- VBA教程
- c++学习笔记十一
- SQLite SQLITE_MASTER
- SVN:冲突解决 合并别人的修改
- Unix/linux学习笔记-------彻底理解管道
- Asphyre 更名pxl 终于全面支持跨平台了.Delphi饭们 激动了吧.
- 一个简单的Inno Setup例子
- Python入门-引号
- vs2012远程调试
- jQuery miniui grid 分页数据后台处理 基于springmvc 和hibernate
- 解决SVN冲突攻略(手册)
- Android多线程(三)
- c++学习笔记十二
- 主键与外键