java.lang.Math.round()学习

本文详细解析了Java Math.round()方法的工作原理,包括其应用规则、特殊情况及与数学四舍五入原则的关系,并通过实例展示了正确的使用方法。

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

<!-- 正文开始 -->

public class MathTest {   
    public static void main(String[] args) {   
        System.out.println("小数点后第一位=5");   
        System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));   
        System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));   
        System.out.println();   
  
        System.out.println("小数点后第一位<5");   
        System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));   
        System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));   
        System.out.println();   
  
        System.out.println("小数点后第一位>5");   
        System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));   
        System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));   
    }   
}  

运行结果:

1、小数点后第一位=5
2、正数:Math.round(11.5)=12
3、负数:Math.round(-11.5)=-11
4、
5、小数点后第一位<5
6、正数:Math.round(11.46)=11
7、负数:Math.round(-11.46)=-11
8、
9、小数点后第一位>5
10、正数:Math.round(11.68)=12
11、负数:Math.round(-11.68)=-12

根据上面例子的运行结果,我们还可以按照如下方式总结,或许更加容易记忆:

1、参数的小数点后第一位<5,运算结果为参数整数部分。
2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。

 

终结:大于五全部加,等于五正数加,小于五全不加。

转载自:http://blog.sina.com.cn/s/blog_4b06743c0100lst3.html

-----------------------------------------------------------------------------

以上是原来的分析~总感觉是有点问题,比如Math.round(-11.5345) == -12; 

参考JDK API 1.6 中讲解如下:

round

public static long round(double a)
返回最接近参数的 long。结果将舍入为整数:加上 1/2,对结果调用 floor 并将所得结果强制转换为 long 类型。换句话说,结果等于以下表达式的值:

 

(long)Math.floor(a + 0.5d)

特殊情况如下:

  • 如果参数为 NaN,那么结果为 0。
  • 如果结果为负无穷大或任何小于等于 Long.MIN_VALUE 的值,那么结果等于 Long.MIN_VALUE 的值。
  • 如果参数为正无穷大或任何大于等于 Long.MAX_VALUE 的值,那么结果等于 Long.MAX_VALUE 的值。

 

参数:
a - 舍入为 long 的浮点值。
返回:
舍入为最接近的 long 值的参数值。

显然,这才是round真正的应用方法:

(long)Math.floor(a + 0.5d)

这样,就没有那么多的猜想与臆断,还得费神去记忆.

Math.round(11.5)=12         (long)Math.floor(11.5+0.5)=12
Math.round(-11.5)=-11  (long)Math.floor(-11.5+0.5)=-11

Math.round(11.5345)=12  (long)Math.floor(11.5345+0.5)=12   
Math.round(-11.5345)=-12 (long)Math.floor(-11.5345+0.5)=-12 

Math.round(11.46)=11  (long)Math.floor(11.46+0.5)=11
Math.round(-11.46)=-11  (long)Math.floor(-11.46+0.5)=-11

Math.round(11.68)=12  (long)Math.floor(11.68+0.5)=12 
Math.round(-11.68)=-12  (long)Math.floor(-11.68+0.5)=-12

.............

嘿嘿~API才是王道!(在设计上还是符合四舍五入-结果变大的原则,呵呵)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值