一:Math类
Math类包含用于执行基本数学运算的方法,如初等函数,对数,平方根和三角函数。
二:Math类常见方法 应用举例
1:运算类
- 求绝对值
- 求幂
- 向上取整
- 向下取整
- 四舍五入
开方 ```java public class Test { public static void main(String[] args) {
//1:绝对值int abs = Math.abs(-5);System.out.println(abs);//2:求幂double pow = Math.pow(2,4);//2的四次方//3:ceil 向上取整//返回>=该参数的最小整数(转成 double);System.out.println(Math.ceil(1.1)); //2.0//4:floor 向下取整//返回<=该参数的最大整数(转成 double)System.out.println(Math.floor(6.3)); // 6.0
// for (int i = 0; i < 100; i++) {// //返回 2 到 7 的数// System.out.println( (int)((Math.random()* 6) + 2));// }//5.round 四舍五入 Math.floor(该参数+0.5)System.out.println(Math.round(5.5));//6.sqrt 求开方System.out.println(Math.sqrt(9));System.out.println(Math.sqrt(-9)); //NaN not a number}
}
<a name="SGjzI"></a>### 2:求随机数```javapublic class Test {public static void main(String[] args) {//随机数//Math.random()返回的是>=0 小于1的值 [0,1)//如果要返回 2 ~ 8 的整数//首先乘6,让它返回 [0,7) 的数int random = Math.random() * 7 ;//然后将随机生出的 [0,7)的数 加 2 ,变成[2.9)random = (Math.random() * 7) + 2;//然后再转换为整数就可以了,转换为整数会舍弃random = (int)((Math.random() * 7) + 2)for (int i = 0; i < 100; i++) {//返回 2 到 7 的数System.out.println( (int)((Math.random()* 6) + 2));}}
