Java面试题----Java基础----Math.round(-1.5)是多少

本文探讨了Java中Math.round()方法的行为,特别是在处理负数时。举例说明了当传入参数为-1.5时,该方法返回的结果是-1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

答案:
-1

实际上,Math.round()方法准确说是“四舍六入”,5要进行判断对待。

 Math.round()的原理是对传入的参数+0.5之后,再向下取整得到的数就是返回的结果,返回值为long型。
 
 这里的向下取整是说取比它小的第一个整数或者和它相等的整数。

 因此Math.round(-1.5)的结果是-1.5 + 0.5 再向下取整,即-1.0取整,结果是-1.

下面是代码示例:

public class Main {
	/**
	 实际上,Math.round()方法准确说是“四舍六入”,5要进行判断对待。
	 Math.round()的原理是对传入的参数+0.5之后,再向下取整得到的数就是返回的结果,返回值为long型。
	 这里的向下取整是说取比它小的第一个整数或者和它相等的整数。

	 因此Math.round(-1.5)的结果是-1.5 + 0.5 再向下取整,即-1.0取整,结果是-1.
	 Math.round(-1.4)的结果是 -1.4 + 0.5 即-0.9 向下取整,结果是-1。
	 同理,Math.round(1.5)即为 1.5 + 0.5 再向下取整,结果是2。

	 Math.floor() 向下取整
	 Math.ceil() 向上取整
	 */
	public static void main(String[] arg){
		System.out.println("----正数-----");
		System.out.println(Math.round(1.0));
		System.out.println(Math.round(1.4));
		System.out.println(Math.round(1.5));
		System.out.println(Math.round(1.6));
		System.out.println("----负数-----");
		System.out.println(Math.round(-1.0));
		System.out.println(Math.round(-1.4));
		System.out.println(Math.round(-1.5));
		System.out.println(Math.round(-1.6));
		System.out.println("---向下取整---");
		System.out.println(Math.floor(1.0));
		System.out.println(Math.floor(1.4));
		System.out.println(Math.floor(1.5));
		System.out.println(Math.floor(1.6));
		System.out.println(Math.floor(-1.0));
		System.out.println(Math.floor(-1.4));
		System.out.println(Math.floor(-1.5));
		System.out.println(Math.floor(-1.6));
		System.out.println("---向取上整---");
		System.out.println(Math.ceil(1.0));
		System.out.println(Math.ceil(1.4));
		System.out.println(Math.ceil(1.5));
		System.out.println(Math.ceil(1.6));
		System.out.println(Math.ceil(-1.0));
		System.out.println(Math.ceil(-1.4));
		System.out.println(Math.ceil(-1.5));
		System.out.println(Math.ceil(-1.6));

	}
}

运行结果

----正数-----
1
1
2
2
----负数-----
-1
-1
-1
-2
---向下取整---
1.0
1.0
1.0
1.0
-1.0
-2.0
-2.0
-2.0
---向取上整---
1.0
2.0
2.0
2.0
-1.0
-1.0
-1.0
-1.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值