Math.floor(Math.random()*3+1)


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.(random/round/cell/floor)隨機數的用法


Math.random()       返回值是一個大於等於0,且小於1的隨機數

Math.random()*N    返回值是一個大於等於0,且小於N的隨機數

 

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隨機數

Math.round(Math.random()*(y-x))+x;   返回x~y的隨機數,包含負數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM