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 为小数位的舍入模式

猜你喜欢

转载自blog.csdn.net/zfliu96/article/details/83447046