Math類和Random類

Math類

成員變量:編程

     (1)public static final double PI :圓周率dom

     (2) public static final double E :天然對數的底數code

成員方法:對象

     (1)public static int abs(int x):絕對值get

            注意:abs()方法的參數能夠是int,float,double,long類型的數據,返回值相應類型的數據變量

     (2)public static double ceil(double x):向上取整,返回double類型隨機數

     (3)public static double floor(double x):向下取整,返回double類型float

     (4)public static int max(int a,int b):最大值方法

            注意:max()方法的參數能夠是int,float,double,long類型的數據,返回值相應類型的數據next

     (5)public static int min(int a,int b):最小值

            注意:min()方法的參數能夠是int,float,double,long類型的數據,返回值相應類型的數據

     (6)public static double pow(double a,double b):a的b次冪

     (7)public static int round(float x):四捨五入

            注意:round()方法的參數能夠是float,double類型的數據

     (8)public static double sqrt(double x):正平方根

     (9)public static double random():隨機數,大於等於 0.0 且小於 1.0 的隨機 double 值(0.0,1.0)

            獲取隨機數:0-1

                             int number = (int)(Math.random())

            獲取隨機數:1-100

                             int number = (int)(Math.random()*100) + 1

            獲取隨機數:start到end之間

                             public static int getRandom(int start,int end){

                               return (int)(Math.random()*(end-start+1))+start;

Random類

random類:用於產生隨機數

注意:通常編程時,習慣使用Math類的random方法來生成隨機數字

構造方法:

   (1)public Random():使用默認的種子,默認種子是當前時間的毫秒值

   (2)public Random(long seed):使用給定的種子。若是用相同的種子建立兩個 Random 實例,則對每一個實例進行相同的方法調用序列,它們將生成並返回相同的數字序列。

成員方法:

       Random類中各方法生成的隨機數字都是均勻分佈的,也就是說區間內部的數字生成的概率是均等的。

     (1)public int nextInt():該方法的做用是生成一個隨機的int值,該值介於int的區間,也就是-231到231-1之間。

     (2)public int nextInt(int n):該方法的做用是生成一個隨機的int值,該值介於[0,n)的區間,也就是0到n之間的隨機int值,包含0而不包含n。

     (3)public boolean nextBoolean():該方法的做用是生成一個隨機的boolean值,生成true和false的值概率相等,也就是都是50%的概率。

     (4)public double nextDouble():該方法的做用是生成一個隨機的double值,數值介於[0,1.0)之間。

     (5)public void setSeed(long seed):該方法的做用是從新設置Random對象中的種子數。設置完種子數之後的Random對象和相同種子數使用new關鍵字建立出的Random對象相同。

相關文章
相關標籤/搜索