使用Math.floor和Math.random取隨機(jī)整數(shù)
轉(zhuǎn)載 2014年11月04日 16:13:34 3087
Math.random():獲取0~1隨機(jī)數(shù)
Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (小于等于 x厚满,且與 x 最接近的整數(shù)劣像。)
其實(shí)返回值就是該數(shù)的整數(shù)位:
Math.floor(0.666) --> 0
Math.floor(39.2783) --> 39
所以我們可以使用Math.floor(Math.random())去獲取你想要的一個(gè)范圍內(nèi)的整數(shù)谜嫉。
如:現(xiàn)在要從1~52內(nèi)取一個(gè)隨機(jī)數(shù):
首先Math.random()52 //這樣我們就能得到一個(gè) >=0 且 <52的數(shù)
然后加1:Math.random()52 + 1 //現(xiàn)在這個(gè)數(shù)就 >=1 且 <53
再使用Math.floor取整
最終: Math.floor(Math.random()*52 + 1)
這就能得到一個(gè)取值范圍為1~52的隨機(jī)整數(shù)了.