基础知识之java math类

Posted by 大雁小鱼的博客 on June 13, 2018

基础知识之Java Math类

Question 1

提问:Math.round(1.5)等于多少?Math.round(-1.5)等于多少?
回答:四舍五入并不像看上去的那么简单,有时候不掌握技巧很难在面试的时候回答上来。计算机中处理四舍五入是这样的:原数上加上0.5然后向下取整数。 所以Math.round(1.5)计算方式是1.5+0.5 = 2,向下取整后得到2,Math.round(-1.5)计算方式是-1.5+0.5 = -1,向下取整后得到-1

public static void main(String[] args) {
    System.out.println(Math.round(1.6));  //1.6 + 0.5 = 2.1 =>2
    System.out.println(Math.round(-1.6)); //-1.6 + 0.5 = -1.1 => -2
    System.out.println(Math.round(1.5));  //1.5+0.5=2.0 =>2
    System.out.println(Math.round(-1.5)); //-1.5+0.5=-1 =>-1
}