html控制台随机数取整,获取随机数、浮点数取整方法
Math.(random/round/cell/floor)隨機數(shù)的用法
Math.random()? ? ? 返回值是一個大于等于0,且小于1的隨機數(shù)
Math.random()*N? ? 返回值是一個大于等于0,且小于N的隨機數(shù)
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隨機數(shù)
Math.round(Math.random()*(y-x))+x;? 返回x~y的隨機數(shù),包含負數(shù)。
假設(shè)arr存著54張牌,
用Math.floor(Math.random()*54)獲取i,j,
然后arr[i]<=>arr[j]兩個交換多次之后即可模擬實現(xiàn)隨機洗牌的效果。
用9張牌舉例:
let arr=[1,2,3,4,5,6,7,8,9]
for(let i = 0;i<5;i++){
let m = Math.floor(Math.random()*9);
let n = Math.floor(Math.random()*9);
let t = arr[m];
arr[m]=arr[n];
arr[n]=t;
}
console.log(arr) //[8, 7, 3, 5, 4, 2, 6, 1, 9]? ?洗牌后會打亂了順序
總結(jié)
以上是生活随笔為你收集整理的html控制台随机数取整,获取随机数、浮点数取整方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 仿微信朋友圈拍照上传
- 下一篇: python中perf_counter_