基础面试题:Math类中提供了三个与取整有关的方法:ceil,floor,round

Math类中提供了三个与取整有关的方法:ceil,floor,round,这些方法的作用于它们的英文名称的含义相对应。

例如:ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11;

floor的英文是地板,该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12;

最难掌握的是round方法,该函数表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.

练习:

  1. Math.round(-11.2)。-11.2+0.5=-10.7 。向下取整为-11。(向下取整就是选择一个比它小的最近的整数。)
  2. Math.round(-11.7)。-11.7+0.5=-11.2。向下取整为-12。(向下取整就是选择一个比它小的最近的整数。)

猜你喜欢

转载自blog.csdn.net/liuzhongyefirst/article/details/83055955