使用Math.floor和Math.random取随机整数
2012-03-07 23:06
260 查看
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的随机整数了.
相关文章推荐
- 使用Math.floor与Math.random取随机整数的方法详解
- 【学习笔记】使用Math.floor与Math.random取随机整数的方法详解
- 使用Math.floor和Math.random取随机整数
- 使用Math.floor和Math.random取随机整数
- 由计算机产生0-9之间的随机整数,用户输入猜测的数据,统计用户猜测的次数。产生随机数可以使用Math.rangom()静态方法,该方法返回正的double类型浮点数位于(0.0 1.0】间。
- jquery Math.random()生成0~10以内随机整数写法
- JS math.random随机数,产生指定范围内的随机整数的代码
- Android使用Math.Random获取随机的颜色值
- 【Android】【小工具】使用Random生成一个指定长度的随机整数列
- Math.random() 生成指定范围随机整数的思考
- jQuery中 Math.random()的用法方法>>产生任意随机整数
- Android使用java的Math.Random获取随机色值
- JS实现使用Math.random()函数生成n到m间的随机数字
- 使用js Math.random()函数生成n到m间的随机数字
- 使用js Math.random()函数生成n到m间的随机数字
- Android使用java的Math.Random获取随机色值
- 设计程序,单击【随机数】按钮,使用Math对象的random函数产生一个0-100之间(含0-100)的随机整数,并在对话框中显示,如下图。单击【计算】按钮,计算该随机数的平方、平方根和自然对数,保留两位小数,并在对话框中显示,如下图。
- js的随机数生成器,不再使用Math.random
- 看点:Math.random()和response.setHeader(String name,String value)的使用实例