Math.round() ceil floor

 

 

Math.round(11.5)等於多少? Math.round(-11.5)等於多少?

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。

 

  System.out.println(Math.round(-11.5)+" "+Math.floor(-11.5+0.5)); //-11
  System.out.println(Math.round(-11.6)+" "+Math.floor(-11.6+0.5));//-12

 

 

 1         // 四舍五入
 2         System.out.println(Math.round(11.4));
 3         System.out.println(Math.round(11.6));
 4         System.out.println(Math.round(-11.2));
 5         System.out.println(Math.round(-11.6));
 6         // 向上取整
 7         System.out.println(Math.ceil(11.6));
 8         System.out.println(Math.ceil(-11.4));
 9         // 向下取整
10         System.out.println(Math.floor(11.6));
11         System.out.println(Math.floor(-11.4));

 

 

// 四舍五入
        System.out.println(Math.round(11.4));//11
        System.out.println(Math.round(11.5));//12
        System.out.println(Math.round(-11.4));//-11
        System.out.println(Math.round(-11.5)); //-11
        System.out.println(Math.round(-11.6));//-12

 

posted on 2014-10-28 10:01  @冰糖  阅读(285)  评论(0编辑  收藏  举报

导航