Fork me on GitHub

转载:使用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的随机整数了.

转自:https://www.cnblogs.com/rexmzk/archive/2012/03/07/2384409.html

posted @ 2018-04-23 20:58  Stefango  阅读(463)  评论(0)    收藏  举报
编辑推荐:
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
· 聊一聊 Linux 上对函数进行 hook 的两种方式
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
阅读排行:
· 推荐 3 种 .NET Windows 桌面应用程序自动更新解决方案
· 一周 Star 破万的开源项目「GitHub 热点速览」
· .NET 10 支持Linux/Unix 的Shebang(Hashbang)
· 上周热点回顾(6.9-6.15)
· 记一次 .NET 某SaaS版CRM系统 崩溃分析
网络威胁 实时地图
点击右上角即可分享
微信分享提示