Math类
😊基本介绍:
Math类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
Math类中源代码 (均为静态方法)
在IDEA中按Ctrl+B可以查看此类的源代码
在源代码中发现里面的方法均为静态方法(主要是为了方便调用)
常用Math类
方法 | 用途 |
---|---|
abs | 绝对值 |
pow | 求幂 |
ceil | 向上取整 |
floor | 向下取整数 |
round | 四舍五入 |
sqrt | 求开方 |
random | 生成一个区间[0,1)的随机数 |
max | 求两个数的最大值 |
min | 求两个数的最小值 |
对Math类进行调用
代码演示
public class MathMethod {
public static void main(String[] args) {
int abs = Math.abs(-99);//求绝对值
System.out.println(abs);
double pow = Math.pow(2,4);//求幂
System.out.println(pow);
double ceil = Math.ceil(-3.123);//向上取整,
// 返回>=该参数的最小整数。
System.out.println(ceil);
double floor = Math.floor(-8.99);//向下取整,
// 放回<=该参数的最大整数。
System.out.println(floor);
long round = Math.round(3.14);//四舍五入 Math.floor(该参数+0.5)
System.out.println(round);
double sqrt = Math.sqrt(9);//开方
System.out.println(sqrt);
for (int i= 0; i < 10; i++) {
double rondom = Math.random();//求随机数
System.out.println(rondom);
}
int max = Math.max(100,123);//求最大值
System.out.println(max);
double min = Math.min(123.123,123.111);//求最小值
System.out.println(min);
}
}
运行截图
如何返回10个区间在[2,7]直接的整数?
public static void main(String[] args) {
for (int i =0 ; i < 10; i++){
int a = 2;
int b = 7;
int rondom1 =(int)( a + Math.random()*(b-a+1));
System.out.println(rondom1);
}
}
运行截图