在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可能就會把邊界漏掉!!!