Java產生隨機數

來源:互聯網
上載者:User

標籤:blog   隨機   ide   opened   sed   double   math   pre   math類   

  對於這個問題,我只放上代碼就可以了,代碼中有注釋,相信聰明的你看得懂的!

  

import java.util.Random; //需要用到這個類包/* * Java產生隨機數 * Time:2017/10/16 * * 方法一:Math類中的random方法可以實現隨機數的產生 * Math.random()方法返回的是帶正號的double值,該值大於0小於1。 * 當然,我們也可以做修改: *                         (int)(Math.random()*10)   返回0-9之間的隨機數 *                         (int)(Math.random()*n)       返回0-n之間的隨機數 *                         (int)(Math.random()*100)+1        返回0-100之間的隨機數,前面返回0-99,加1就是0-100了 * * 方法二:Random類 * 在產生隨機數之前,必須先寫:Random random=new Random(); * random.nextInt();    返回的是int類型範圍內的隨機數 * random.nextInt(10);    返回的是0-9之間的隨機數 * random.nextInt(100)+1;    返回的是1-100之間的隨機數 * random.nextInt(n)+m;        返回的就是m到m+n-1之間的隨機數 */public class RandomNum {    public static void main(String[] args) {        //方法一        double num=Math.random();//返回double類型的數字        System.out.println(num);        //以下產生int類型的如果不把方法括起來,返回的只能是0        int num1=(int)(Math.random()*10);//返回0-9之間的隨機數        System.out.println(num1);        int num2=(int)(Math.random()*100);//返回0-99之間的額數        System.out.println(num2);        //方法二        Random random=new Random();//方法二就必須寫這句,random只是個名字,自己取        int s=random.nextInt();//產生一個int類型的隨機數        System.out.println("產生的隨機數為:"+s);        int s2=random.nextInt(10);//產生0-9之間的隨機數        System.out.println(s2);    }}
View Code

  運行結果為:

  

0.3248983535648986691產生的隨機數為:-19098713886

 

Java產生隨機數

聯繫我們

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