Math - 数学类
1、理解
Math 类是 Java 中的一个内置类,它位于 java.lang 包中,因此无需显式导入即可使用。Math 类提供了许多用于执行基本数学运算和操作的静态方法,如三角函数、指数函数、对数函数、舍入函数等。由于 Math 类中的方法都是静态的,因此可以直接通过类名来调用它们,而无需创建 Math 类的实例。
1、基本算术运算
Math.abs(int a):返回整数a的绝对值。
Math.max(int a, int b)和Math.min(int a, int b):返回两个整数中的最大值和最小值。
Math.pow(double a, double b):返回a的b次幂的值。
Math.sqrt(double a):返回a的正平方根。
2、三角函数
Math.sin(double a):返回角度a(以弧度为单位)的正弦值。
Math.cos(double a):返回角度a(以弧度为单位)的余弦值。
Math.tan(double a):返回角度a(以弧度为单位)的正切值。
3、指数和对数函数
Math.exp(double a):返回e的a次幂的值,其中e是自然对数的底数。
Math.log(double a):返回a的自然对数(以e为底)。
Math.log10(double a):返回a的以 10 为底的对数值。
4、舍入和取整
Math.round(double a):返回最接近a的整数。如果a是整数或离整数更近,则直接返回该整数。
Math.ceil(double a):返回大于或等于a的最小整数(向上取整)。
Math.floor(double a):返回小于或等于a的最大整数(向下取整)。
5、随机数生成
Math.random():返回一个伪随机数,该数大于等于 0.0 且小于 1.0。
6、其他常用方法
Math.PI:表示圆周率的常量,其值接近 3.141592653589793。
Math.toRadians(double angdeg):将角度转换为弧度。
Math.toDegrees(double angrad):将弧度转换为角度。
2、案例
1、案例一
package com.qf.math_class;public class Test01 {/*** 知识点:Math - 数学类* Math 类提供了一序列基本数学运算和几何函数的方法。* Math类是final类,并且它的所有成员变量和成员方法都是静态的。*/public static void main(String[] args) {System.out.println("求次方:" + Math.pow(3, 2));//9.0System.out.println("求平方根:" + Math.sqrt(9));//3.0System.out.println("获取绝对值:" + Math.abs(-100));//100System.out.println("向上取整(天花板):" + Math.ceil(1.1));//2.0System.out.println("向下取整(地板):" + Math.floor(1.9));//1.0System.out.println("四舍五入:" + Math.round(1.5));//2System.out.println("最大值:" + Math.max(10, 20));//20System.out.println("最小值:" + Math.min(10, 20));//10System.out.println("获取随机值(0包含~1排他):" + Math.random());//0.39661220991942137//需求:随机出1~100的数字System.out.println((int)(Math.random()*100) + 1);}
}2、案例二
package com.qf.math_class;public class Test02 {/*** 知识点:Math类面试题*/public static void main(String[] args) {//-2的31次方System.out.println("获取int类型最小值:" + Integer.MIN_VALUE);//-2147483648//2的31次方-1System.out.println("获取int类型最大值:" + Integer.MAX_VALUE);//2147483647//面试题:Math类的abs()是否会返回负数?System.out.println(Math.abs(Integer.MIN_VALUE));//-2147483648}
}3、案例三
package com.qf.math_class;//静态导入:将类里的静态属性和方法导入到本类来,成为本类自己的静态属性和方法
import static java.lang.Math.*;public class Test03 {/*** 知识点:静态导入* * 缺点:可读性不高*/public static void main(String[] args) {System.out.println("获取绝对值:" + abs(-100));System.out.println("向上取整(天花板):" + ceil(1.1));System.out.println("向下取整(地板):" + floor(1.9));}public static int abs(int i){return 1234567890;}}