java 中的 Math.round(-1.5) 等于多少?

这篇博客探讨了Java中Math.round方法的行为,特别是它如何进行四舍五入操作。当传入参数为负数时,如Math.round(-1.5),方法会返回最接近的最大整数,即-1。通过示例代码展示了该方法在不同情况下的结果,帮助理解其计算规则。

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

面试题汇总

java 中的 Math.round(-1.5) 等于多少?

这道题目的答案是 -1.

其实这道题目考察的主要知识点就是:Math.round方法的概念以及返回值类型。

注意:Math的round方法是四舍五入,如果参数是负数,则往大的数如,Math.round(-1.5)=-1,如果是Math.round(1.5)则结果为2

计算规则为:

  1. 如果参数大于 Long.MAX_VALUE 则返回Long.MAX_VALUE
  2. 如果参数小于Long.MIN_VALUE 则返回Long.MIN_VALUE
  3. 如果参数为NaN则返回0
  4. 其余值则返回接近于当前参数的最大整数值。

所以Math.round(-1.5)返回的是最接近的最大整数-1。

例:

public class test {
	public static void main(String[] args){
		System.out.println(Math.round(1.3));   //1
		System.out.println(Math.round(1.4));   //1
		System.out.println(Math.round(1.5));   //2
		System.out.println(Math.round(1.6));   //2
		System.out.println(Math.round(1.7));   //2
		System.out.println(Math.round(-1.3));  //-1
		System.out.println(Math.round(-1.4));  //-1
		System.out.println(Math.round(-1.5));  //-1
		System.out.println(Math.round(-1.6));  //-2
		System.out.println(Math.round(-1.7));  //-2
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值