Math.random()和Math.round()總結

在java、c#、js裏面都用到了Math.random()這個函數,每次使用都要百度如何取範圍,今天又需要了,寫下來當總結。

Math.random()用法

Math.random()是令系統隨機選取大於等於 0.0 且小於 1.0 的僞隨機 double 值。

返回指定範圍的隨機數[m,n]的公式:Math.random()*(n-m+1)+m;

Math.round()用法

Math.round()就是括號內的數+0.5之後,向下取值


【demo】隨機取1-10之間的數

var a = Math.round(Math.random()*9+1);

注意:因爲Math.random()返回的是<1的數,是不包括1的,如果不加Math.round可能就會把邊界漏掉!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章