math.round(Java中Math.round函数的示例分析)

发布时间:2025-12-10 23:05:41 浏览次数:1

1.代码如下:

publicclassTestMathRound{publicstaticvoidmain(String[]args){System.out.println("小数点后第一位=5");System.out.println("正数:Math.round(11.5)="+Math.round(11.5));//12System.out.println("负数:Math.round(-11.5)="+Math.round(-11.5));//-11System.out.println();System.out.println("小数点后第一位<5");System.out.println("正数:Math.round(11.46)="+Math.round(11.46));//11System.out.println("负数:Math.round(-11.46)="+Math.round(-11.46));//-11System.out.println();System.out.println("小数点后第一位>5");System.out.println("正数:Math.round(11.68)="+Math.round(11.68));//12System.out.println("负数:Math.round(-11.68)="+Math.round(-11.68));//-12}}

2.结果如下,可以自己运行。

3.本来以为是四舍五入,取最靠近的整数,查了网上说有四舍六入五成双,最后还不如看源码。源码如下:

publicstaticlonground(doublea){if(a!=0x1.fffffffffffffp-2)//greatestdoublevaluelessthan0.5return(long)floor(a+0.5d);elsereturn0;}

我们看到round函数会默认加0.5,之后调用floor函数,然后返回。floor函数可以理解为向下取整。

4.综上,Math.round函数是默认加上0.5之后,向下取整。

感谢各位的阅读!关于“Java中Math.round函数的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

math.round
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477