Math类中提供了三个与取整有关的方法:ceil、floor、round,这些方法的作用与它们的英文名称的含义相对应,例如,ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.3)的结果是-11;floor的英文意义是地板,该方法就表示向下取整,Math.ceil(11.6)的结果为11,Math.ceil(-11.6)的结果是-12;最难掌握的是round方法,它表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。
1.先说下怎么理解
round()方法可以这样理解:
将括号内的数+0.5之后,向下取值,
比如:round(3.4)就是3.4+0.5=3.9,向下取值是3,所以round(3.4)=3;
round(-10.5)就是-10.5+0.5=-10,向下取值就是-10,所以round(-10.5)=-10
扩展:常用的三个
Math.ceil求最小的整数,但不小于本身.
ceil的英文意义是天花板,该方法就表示向上取整,
例子:
所以,Math.ceil(11.3)的结果为12,Math.ceil(-11.3)的结果是-11;
Math.floor求最大的整数,但不大于本身.
floor的英文意义是地板,该方法就表示向下取整,
例子:
floor的英文意义是地板,该方法就表示向下取整,
public static void main(String[] args) { System.out.println("Math.round(-11.5)="+Math.round(-11.5)); System.out.println("Math.round(11.5)="+Math.round(11.5)); System.out.println("Math.round(-12.5)="+Math.round(-12.5)); System.out.println("Math.round(12.5)="+Math.round(12.5)); // Math.round()是四舍五入,往x轴正方向取值 }
public static int round(float a) { if (a != 0x1.fffffep-2f) // greatest float value less than 0.5 return (int)floor(a + 0.5f); else return 0; } /**********************************/ public static long round(double a) { if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 return (long)floor(a + 0.5d); else return 0; } //可以看到,round()的四舍五入的做法是在参数上加上0.5再向下取整
题目大概是问Math.Round(11.5);和Math.Round(-11.5);返回值是多少?
原来不是四舍五入这么简单,其实是四舍六入,但是五是很有讲究的。要是遇到五则取离前一位最近的偶数。比如,这条题目,11.5返回值就是12.0;-11.5返回值就是-11.0;
但是这里其实也不是这么简单:
看下面的例子:Math.Round(3.44, 1); //Returns 3.4.Math.Round(3.45, 1); //Returns 3.4.Math.Round(3.46, 1); //Returns 3.5.依照他的例子得到的是"五舍六入",我改变了一下数字得到的结果将完全改变。
Math.Round(3.445, 1); //Returns 3.4.
Math.Round(3.455, 1); //Returns 3.5.
Math.Round(3.465, 1); //Returns 3.5.
Math.Round(3.450, 1); //Returns 3.4.(补0是无效的)
Math.Round(3.4452, 2); //Returns 3.45.
Math.Round(3.4552, 2); //Returns 3.46.
Math.Round(3.4652, 2); //Returns 3.47.-----------------------------------------------
Math.Round(3.44, 1) = 3.4
Math.Round(3.45, 1) = 3.4
Math.Round(3.46, 1) = 3.5
-----------------------------------------------
Math.Round(3.54, 1) = 3.5
Math.Round(3.55, 1) = 3.6
Math.Round(3.56, 1) = 3.6
-----------------------------------------------
Math.Round(3.64, 1) = 3.6
Math.Round(3.65, 1) = 3.6
Math.Round(3.66, 1) = 3.7
-----------------------------------------------
Math.Round(3.74, 1) = 3.7
Math.Round(3.75, 1) = 3.8
Math.Round(3.76, 1) = 3.8
这种舍入方法叫做银行家舍入(Banker'sRound),这就是已经规定下来的标准、Round的标准、世界的标准。这里,其实是根据方法的行为遵循 IEEE 标准 754 的第 4 节。这种舍入有时称为就近舍入或银行家舍入;
总结的口诀是:四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍去,五前为奇要进一!
按照这样的口诀去做确实能验证以上的返回结果!