先簡單理解成四捨五入
math.round(4.5) = 5;
math.round(5.3) = 5;
math.round(0.1) = 0;
這很好理解,對吧,小學生都很容易掌握的四捨五入。但是當round()中的值爲負數的時候就容易犯錯了
先看
math.round(-10.6) = -11
math.round(-10.5) = -10 而不是-11 不應該四舍五嗎
注意,這裏是負數。round()方法你可以這樣理解:就是括號內的數+0.5之後,向下取值,-10.6+0.5=-10.1 向下取值就是-11.同理-10.5+0.5=-10.向下取值就是-10.
當然你也可以用初中常用的數軸來區別: -11<= (-10.6+0.5) <=-10,固應該取值-11. -10 <= (-10.5+0.5) <=-9 固取值-10.這跟正數是一樣的 5<= (4.5+0.5) <= 6 取值5
5<= (5.3+0.5) <= 6 取值5一樣。
看看源代碼
public static long round(double a) {
return (long)floor(a + 0.5d);
}
其原理就是這樣。四捨五入。 這樣理解就不容易犯錯了。