隨機數Math.floor(Math.random()*52+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的隨機整數了.


免責聲明!

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



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