您的位置:首页 > 编程语言 > Java开发

java中round()函数,floor()函数,ceil()函数的返回值

2017-08-13 17:16 399 查看
不太熟悉的是round()函数的一些边缘值,比如Math.round(11.5)是多少,所以测试了一下。当前,之前对于向上取整和向下取整也有误解地方,一直以为返回数字应该为int类型,但是看了源码才知道返回值是double类型。

测试代码:

/**
* created by cxh on 17/7/27
*/

public class TempTest {
public static void main(String[] args) {
/**
* 测试Math.round(x)输出数字;他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整
* 如果x距离相邻两侧的整数距离不一样,则取距离近的那个数字;
* 如果x距离相邻两侧的整数距离一样,则取真值大的那个数字(即为大于x的那个数字)
*/
System.out.println(Math.round(-11.3));// -11
System.out.println(Math.round(-11.5));//-11
System.out.println(Math.round(-11.6));//-12
System.out.println(Math.round(11.3));//11
System.out.println(Math.round(11.5));//12
System.out.println(Math.round(11.6));//12

/**
* 向下取整,返回的是一个double值
*/
System.out.println(Math.floor(11.8));//11.0
System.out.println(Math.floor(11.5));//11.0
System.out.println(Math.floor(11.1));//11.0
System.out.println(Math.floor(-11.8));//-12.0
System.out.println(Math.floor(-11.5));//-12.0
System.out.println(Math.floor(-11.1));//-12.0

/**
* 向上取整,返回的是一个double值
*/
System.out.println(Math.ceil(11.8));//12.0
System.out.println(Math.ceil(11.5));//12.0
System.out.println(Math.ceil(11.1));//12.0
System.out.println(Math.ceil(-11.8));//-11.0
System.out.println(Math.ceil(-11.5));//-11.0
System.out.println(Math.ceil(-11.1));//-11.0
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: