js中隨機數的形成需要的用到Math.random(),上一篇博客中提到了它,指的是0~1之間數,那么今天要說的其實是隨機整數的形成,所以還要用到Math.round()的方法,這個是四舍五入的方法。
接下來看一系列公式代碼:
window.onload=function(){ Math.round(3.4); // 3 四舍五入的方法 Math.random(); // 0~1之間的數 //0-1之間的整數 Math.round(Math.random()); //0-10之間整數公式 Math.round(Math.random()*10); //5-10之間整數公式 Math.round(Math.random()*5+5); //10-20之間整數公式 Math.round(Math.random()*10+10); //20-100之間整數公式 Math.round(Math.random()*80+20); //0-x之間整數公式 Math.round(Math.random()*x); //x-y之間整數公式 Math.round(Math.random()*(y-x)+x); //1-x之間整數公式 Math.ceil( Math.random()*x); //Math.ceil()向上取整 };
我覺得這些是常見的一些會應用到的公式,了解其原理的更好,若是不了解那便記牢即可,應該會用到。
好了,今天就這樣了!
