Java中的隨機函數

來源:互聯網
上載者:User

最近做一個項目需要用到隨機數,需求是在整數1-9中間隨機播放一個數字。

於是google,好多人告之使用Math.random()。結果寫成如下:int p = (int) (Math.random() * 9); 結果就是1和9永遠隨機不到。這是錯的。太坑爹了。

 於是後來查了Javase docs. 對於這個函數,是這樣講的:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0

因為less than 1.0, 所以強制轉化到integer,  上面的p是永遠不會為9的。0倒是可以隨機到的,因為強制轉化時會取下整。

最後找到這個函數Random.nextInt(int n) 這個函數:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

比如上訴的需求可寫為: Random ran = new Random(); int p =ran.nextInt(9)+1;  這樣能夠得到想要的結果。

如果要對任意輸入的正整數範圍取隨機,則如下: 

 int createRandom(int min, int max) {Random random = new Random();return random.nextInt(max-min+1)+ min;}

 十分簡單,但是之前我照抄網路上的代碼,結果悲劇了,調試了半天。以後還是看官方的 docs 為好。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.