常用类-Math类
Math 类提供了一序列基本数学运算和几何函数的方法。
Math类是类,并且它的所有成员变量和成员方法都是静态的。
1 Math类的常量和常用方法
常量
static double E
比任何其他值都更接近 e(即自然对数的底数)的 double 值。static double PI
比任何其他值都更接近 pi(即圆的周长与直径之比)的 double 值。常用方法:Math内的所有方法均为静态
double sin(double a) 计算角a的正弦值 double cos(double a) 计算角a的余弦值 double pow(double a,double b) 计算a的b次方 double sqrt(double a) 计算给定值的平方根 int abs(int a) 计算int类型值a的绝对值,也接收long、float和double类型的参数 double ceil(double a) 返回大于等于a的最小整数的double值 double floor(double a) 返回小等于a的最大整数的double值 int max(int a,int b) 返回a和b中的较大值,也接收long、float和double类型的参数 int min(int a,int b) 返回a和b中的较小值,也接收long、float和double类型的参数 int round(float a) 四舍五入返回整数 double random() 返回带正号的double值,该值大于等于0.0且小于1.0
package com.qf.math_class;public class Test01 {*/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 Math相关面试题
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 静态导入(了解)
当使用一个类里面的静态方法或者静态变量时,每次都需要写类名。如果不想写类名,想直接写方法名或者变量名,则可以考虑使用静态导入
语法:import static 包名.类名.*; //导入该类下的所有静态方法和常量8
例如:import static java.lang.Math.*; //导入Math下的所有方法和变量(包括常量)
则代码中可以直接使用方面和变量名,而不需要前缀Math。
如:max(3,4);
package com.qf.math_class;//静态导入:将类里的静态属性和方法导入到本类来,成为本类自己的静态属性和方法
import static java.lang.Math.*;public class Test03 {/*** 知识点:静态导入* * 缺点:可读性不高*/public static void main(String[] args) {System.out.println("获取绝对值:" + abs(-100));//100System.out.println("向上取整(天花板):" + ceil(1.1));//2System.out.println("向下取整(地板):" + floor(1.9));//1}public static int abs(int i){return 1234567890;}}