(一)常用方法
数学类 - Math类
-
Math类提供了基本数学运算和几何函数的方法
-
Math类是final类,没有子类
-
Math类中所以的属性和方法都是静态的
方法 | 含义 |
---|---|
double sin (double a) | 计算角a的正弦值 |
double cos (double a) | 计算角a的余弦值 |
double tan (double a) | 计算a的b次方 |
double qart (double a) | 计算给定值的平方根 |
int abs (int a) | 计算a的绝对值,也接受long、float和double类型的参数 |
double cell (double a) | 返回大于等于a的最小整数的double值 |
double floor (double a) | 返回小于等于a的最小整数的double值 |
int max (int a,int b) | 返回int值的较大值,也接受long、float和double类型的参数 |
int min(int a,int b) | 返回int值的较小值,也接受long、float和double类型的参数 |
int round(float a) | 四舍五入的返回整数 |
double random() | 返回带正好的double值,该值大于等于0.0且1.0 |
(二)具体使用
public class test01 {
public static void main(String[] args) {
System.out.println("求次方:"+ Math.pow(2,3));//8.0
System.out.println("求平方根"+ Math.sqrt(9));//3.0
System.out.println("求绝对值" + Math.abs(-2332));//2332
System.out.println("向上取整" + Math.ceil(1.3));//2.0
System.out.println("向下取整" + Math.floor(3.2));//3.0
System.out.println("四舍五入" + Math.round(56.3));//56
System.out.println("最大值" + Math.max(47,238));//238
System.out.println("最小值" + Math.min(47,238));//47
System.out.println("随机值"+ Math.random());//0-1的随机数
}
}
(三)随机案例
public class test02 {
public static void main(String[] args) {
//随机出1-100的数字
int num = (int)(Math.random()*100)+1;
System.out.println(num);
}
}
(四)abs深入
Math.abs()会返回负数
数据是有范围的,当数据超出返回之后,运用该方法就会返回负数
public class test03 {
public static void main(String[] args) {
System.out.println(Math.abs(-2147483648));//-2147483648
System.out.println(Math.abs(2147483647+1));//-2147483648
}
}
(五)静态导入
将Math类中所有的静态属性和方法导入到本类型中,这些静态方法和属性成为本类的属性和方法,在调用时不需要再用类名调用
import static java.lang.Math.*;
public class test01 {
public static void main(String[] args) {
System.out.println("求次方:"+ pow(2,3));//8.0
System.out.println("求平方根"+ sqrt(9));//3.0
}
}
注意:静态导入就近原则,先查看本来自己是否有该方法,如果有就直接调用,如果没有就找静态导入类中方法。
缺点:不确定方法式本类的还是静态导入类的,可读性比较差。