关于Math的floor,round和ceil的方法面试题

来源:互联网 发布:c语言函数规则 编辑:程序博客网 时间:2024/06/04 18:00

关于Math的floor,round和ceil方法面试题

首先,明确一下概念。

floor() :向下取整

ceil() :向上取整

round() : 表示 “四舍五入” 在原来的数字上加0.5再向下取整。


解释:

1. 向下取整:向下取整就是将小数点后面的数字抹掉。

2. 向上取整:向上取整就是将小数点后面的数字抹掉,给个位数字加1。

3. 四舍五入:与小学学过的概念有所不同:

这里是在原来的数字上加0.5,然后再向下取整。


举例说明:

public class Demo {public static void main(String[] args) {double ceil = Math.ceil(11.45);//向上取整double floor = Math.floor(11.45);//向下取整long round = Math.round(11.45);//四舍五入 在原来数字上加0.5,然后向下取整。System.out.println(ceil);System.out.println(floor);System.out.println(round);}}

输出分别是: 12.0、11.0、11