1. 程式人生 > >Java中Math、Random、BigInteger、BigDecimal類

Java中Math、Random、BigInteger、BigDecimal類

文章目錄

Math類

1、 成員變數
 a) public static final double PI
 b) public static final double E
2、成員方法(注意返回值型別)
 a) public static int abs(int a);絕對值
 b) public static double floor(double a)向下取整
 c) public static double ceil(double a)向上取整
 d) public static int max(int a,int b) a、b的最大值
 e) public static int min(int a,int b) a、b的最小值
 f) public static double pow(doublie a,double b) a的b次冪
 g) public static double random()隨機數0.0到1.0不包括右邊包括左邊
 h) public static int round(float a)四捨五入
 i) public static double sqrt(double a)返回正平方根

Random類

1、 構造方法
 a) public Random();沒有種子,用的是預設種子,是當前時間的毫秒值
 b) public Random(long seed);給出指定的種子
  i. 給定種子後,相同種子每次得到的隨機數相同
2、 成員方法
 a) public int nextInt();返回一個int範圍的隨機數
 b) public int nextInt(int n)返回的是[0,n)範圍內的隨機數
3、 用法
 a) Random r=new Random();
 b) int num =r.nextInt(100)

BigInteger類

需要導包java.math.BigInteger,可以表示不可變的任意精度的整數,都以二進位制補碼形式表示BigInteger
1、 可以讓超過Integer範圍內的資料進行運算
2、 構造方法
 a) public BigInteger(String val)
3、 成員方法
 a) public BigInteger add(BigInteger val);加
 b) public BigInteger subtract(BigInteger val);減
 c) public BigInteger multiply(BigInteger val);乘
 d) public BigInteger divide(BigInteger val);除
 e) public BigInteger [] divideAndRemainder(BigInteger val)返回商和餘數的陣列
  i. 其中BigInteger[0]為商,BigInteger[1]為餘數

BigDecimal類

1、 在運算時float、double型別很容易丟失精度(float、double的儲存方式和整數不一樣,大多數是帶有有效數字的),為了能精確的表示浮點數,所以用BigDecimal類。
2、 BigDecimal:不可變的、任意精度的有符號十進位制數,可以避免精度丟失問題。
3、 構造方法:
 a) public BigDecimal(String val);
4、 成員方法:
 a) public BigDecimal add(BigDecimal a);
 b) public BigDecimal subtract(BigDecimal a);
 c) public BigDecimal multiply (BigDecimal a);
 d) public BigDecimal divide (BigDecimal a);
 e) public BigDecimal divide (BigDecimal a,int scale,int roundingMode);
  i. scale為小數位位數,roundingMode 為小數位的舍入模式