java floor,ceil和round方法

Math.floor():返回值是double類型的,返回的是不大於它的最大整數spa

舉例:    code

1 double x = Math.floor(5.8);
2 System.out.println(x);    //輸出結果:5.0     
3 double x = Math.floor(-2.5);
4 System.out.println(x);   //輸出結果:-3.0

 

Math.ceil():返回值是double類型的,返回的是不小於它的最小整數blog

舉例:class

1 double x = Math.ceil(5.8);
2 System.out.println(x);       //輸出結果:6.0
3 double x = Math.ceil(-2.5);
4 System.out.println(x);       //輸出結果:-2.0

 

Math.round():返回值是 int/long 類型的,返回的是四捨五入或四捨六入後的整數di

      (或者理解爲Math.floor(x+0.5):在原來的數上+0.5再向下取整)co

舉例:

1 int x = Math.round(1.6);    
2 System.out.println(x);        //輸出結果:2
3 int x = Math.round(1.3);    
4 System.out.println(x);        //輸出結果:1
5 
6 int x = Math.round(-1.6);    
7 System.out.println(x);        //輸出結果:-2
8 int x = Math.round(-1.5);    
9 System.out.println(x);        //輸出結果:-1
相關文章
相關標籤/搜索