在javascript中隨機數 math random如何產生指定範圍數值的隨機數,mathrandom

來源:互聯網
上載者:User

在javascript中隨機數 math random如何產生指定範圍數值的隨機數,mathrandom

今天有朋友向我請教:JavaScript 怎麼產生指定範圍數值隨機數。Math.random() 這個方法相信大家都知道,是用來產生隨機數的。不過一般的參考手冊時卻沒有說明如何用這個方法來產生指定範圍內的隨機數。這次我就來詳細的介紹一下Math.random(),以及如何用它來產生制定範圍內的隨機數。

w3school的random()教程

定義和用法

random() 方法可返回介於 0 ~ 1 之間的一個隨機數。

文法

Math.random()

傳回值

0.0 ~ 1.0 之間的一個偽隨機數。

執行個體

在本例中,我們將取得介於 0 到 1 之間的一個隨機數:

<script type="text/javascript">document.write(Math.random());</script>// 輸出:0.15246391076246546

如何產生指定範圍值的隨機數

看完w3school的教程,應該知道Math.random()方法的基本用法了。

利用 parseInt()、Math.floor() 或者 Math.ceil()進行四捨五入處理

我們看到,直接使用Math.random()方法,產生的是一個小於1的數,所以:

Math.random()*5

得到的結果是一個小於5的隨機數。而我們通常希望得到的是0-5之間的整數,所以我們需要對得到的結果四捨五入處理一下,從而得到我們期望的整數。parseInt()、Math.floor()和Math.ceil()都可以起到四捨五入的作用。

var randomNum = Math.random()*5;alert(randomNum); // 2.9045290905811183 alert(parseInt(randomNum,10)); // 2alert(Math.floor(randomNum)); // 2alert(Math.ceil(randomNum)); // 3

由測試的代碼我們可以看到,parseInt()和Math.floor()的效果是一樣的,都是向下取整數部分。所以parseInt(Math.random()*5,10)和Math.floor(Math.random()*5)都是產生的0-4之間的隨機數,Math.ceil(Math.random()*5)則是產生的1-5之間的隨機數。
產生指定範圍數值隨機數

所以,如果你希望產生1到任意值的隨機數,公式就是這樣的:

// max - 期望的最大值parseInt(Math.random()*max,10)+1;Math.floor(Math.random()*max)+1;Math.ceil(Math.random()*max);

如果你希望產生0到任意值的隨機數,公式就是這樣的:

// max - 期望的最大值parseInt(Math.random()*(max+1),10);Math.floor(Math.random()*(max+1));如果你希望產生任意值到任意值的隨機數,公式就是這樣的:// max - 期望的最大值// min - 期望的最小值 parseInt(Math.random()*(max-min+1)+min,10);Math.floor(Math.random()*(max-min+1)+min);

看完本篇是不是收穫頗多啊,對於隨機數 math random的使用是不是明白了,希望本篇文章能夠給您帶來協助,謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.