Math类
工具类,包含常用于执行的基本数学运算的方法
常量
// E: 自然数的底数
System.out.println(Math.E);
// PI: 圆周率
System.out.println(Math.PI);
常用的方法:
- 取绝对值:
System.out.println(Math.abs(-3.14));//3.14
- 求a的b次幂
System.out.println(Math.pow(2, 3));//8
- 求最大值最小值
Math.max(double a, double b);
Math.min(double a, double b);
- 获取[0,1)之间的浮点型随机数
Math.random();
5.去一个浮点型数据整数区间内的上限和下限
double a = 3.556
System.out.println(Math.ceil(a));//4.0
System.out.println(Math.floor(a));//3.0
- 四舍五入取整,返回一个int类型的数据
System.out.println(Math.round(a * 100) *0.01);//3.56
Random类
随机数类
常用方法:
- 构造方法
//根据当前时间的微秒值去调用有参构造作为随机种子
Random random = new Random();
- next()系列方法
nextInt()\nextInt(int bound)//设置上限
注意事项
- 使用无参构造,默认使用当前时间作为随机数的种子
- 如果使用有参构造,将使用指定种子
- 多个Random对象,如果使用的种子相同,取得的随机数也相同。
@Test
public void test1() {
Random random = new Random();
int i = random.nextInt(); // 整个int取值范围的随机数
System.out.println(i);
int j = random.nextInt(2); // 指定范围取随机整数[0,1],不包含负数
System.out.println(j);
}
@Test
public void test2() {
Random random1 = new Random(1);
Random random2 = new Random(1);
System.out.println(random1.nextInt() == random2.nextInt());//true
}