Math类的三个方法比较: floor() ceil() round()
1 public class Test { 2 public static void main(String[] args) { 3 double d1 = 3.4, d2 = 3.6; //正数 4 double d3 = -3.4, d4 = -3.6; //负数 5 6 float f1 = 4.4F, f2 = 4.6F; //正数 7 float f3 = -4.4F, f4 = -4.6F; //负数 8 9 //floor()方法只能接收double类型,返回double类型 10 //向下取整,返回小于参数的最大整数 11 System.out.println(Math.floor(d1));//3.0 12 System.out.println(Math.floor(d2));//3.0 13 System.out.println(Math.floor(d3));//-4.0 14 System.out.println(Math.floor(d4));//-4.0 15 16 17 //ceil()方法只能接收double类型,返回double类型 18 //向上取整,返回大于参数的最小整数 19 System.out.println(Math.ceil(d1));//4.0 20 System.out.println(Math.ceil(d2));//4.0 21 System.out.println(Math.ceil(d3));//-3.0 22 System.out.println(Math.ceil(d4));//-3.0 23 24 25 //round()方法可以接收double类型,返回long类型 26 //表示“四舍五入”,算法为Math.floor(x+0.5),即将参数加上0.5后再向下取整 27 System.out.println(Math.round(d1));//3 28 System.out.println(Math.round(d2));//4 29 System.out.println(Math.round(d3));//-3 30 System.out.println(Math.round(d4));//-4 31 32 //round()方法可以接收float类型,返回int类型 33 System.out.println(Math.round(f1));//4 34 System.out.println(Math.round(f2));//5 35 System.out.println(Math.round(f3));//-4 36 System.out.println(Math.round(f4));//-5 37 } 38 }
The only way to do great work is to love what you do.