java Math类

位于java.lang包

1.常用方法

 1 public class TestMath {
 2     public static void main(String[] args) {
 3         System.out.println("绝对值:"+Math.abs(-23)+"\t"+Math.abs(0));//23    0
 4         System.out.println("向上取整再转double:"+Math.ceil(23.00001)+"\t"+Math.ceil(-9.999999));//24.0    -9.0
 5         System.out.println("向下取整数再转double:"+Math.floor(23.99999)+"\t"+Math.floor(-23.00001));//23.0    -24.0
 6         System.out.println("最值:"+Math.max(20, 10)+"\t"+Math.min(3, 40));//20    3
 7         System.out.println("5的2次方:"+Math.pow(5, 2));//25
 8         System.out.println("随机数[0,1):"+Math.random());
 9         int ran=(int)(Math.random()*9000)+1000;
10         System.out.println("1000-9999之间的随机数:"+ran);
11         System.out.println("四舍五入:"+Math.round(34.567)+"\t"+Math.round(34.345));//35   34
12         System.out.println("开方:"+Math.sqrt(4));//2.0                
13     }
14 }

 

2.静态导入

类的方法都是静态的,通过静态导入使用时省略类名前缀,当与类中定义的方法相同时使用的是定义的方法,此时在想使用要添加前缀

 1 import static java.lang.Math.*;
 2 public class TestStaticImport {
 3     public static void main(String[] args) {
 4         System.out.println(abs(-20));//20
 5         System.out.println(Math.abs(-20));//20
 6     }
 7     /*public static int abs(int number){
 8         return number;
 9     }*/
10 }

 

posted @ 2019-02-10 10:41  北风吹沙  阅读(337)  评论(0编辑  收藏  举报