发布时间:2025-12-10 19:44:20 浏览次数:4
关于Math.round()方法分析「终于解决」Math.round()方法是四舍五入,原理是在原数的基础上加0.5,然后向下取整(非常重要),如果进行判断只是记住了四舍五入很多情况下是错误的,下面进行分析Math.round(-2.5),四舍五入之后是-3,你或许说前面有负号,应该是-2,那么Math.round(-2.4)多少呢?是不是就应该是-3了,Math.round(-2.6)是多少呢?-2吧。 这都是有错误的结果,如果是四舍五入取进行判断,正数没有任何问题,但是如果是负数就不确定了。所以现在用原理去进行分析计算。Math.
Math.round()方法是四舍五入,原理是在原数的基础上加0.5,然后向下取整(非常重要),如果进行判断只是记住了四舍五入很多情况下是错误的,下面进行分析
Math.round(-2.5),四舍五入之后是-3,你或许说前面有负号,应该是-2,那么Math.round(-2.4)多少呢?是不是就应该是-3了,Math.round(-2.6)是多少呢?-2吧。
这都是有错误的结果,如果是四舍五入取进行判断,正数没有任何问题,但是如果是负数就不确定了。
所以现在用原理去进行分析计算。
Math.round(-2.5),-2.5+0.5=-2向下取整为-2
Math.round(-2.55),-2.55+0.5=-2.05向下取整为-3
Math.round(-2.4),-2.4+0.5=-1.9向下取整去-2
Math.round(-2.6),-2.6+0.5=-2.1向下取整为-3
Math.round(-2.500001),-2.500001+0.5=-2.000001向下取整为-3
正数按照四舍五入判断没有任何问题
总结:按照原理去进行判断,不会出现任何问题,如果按照四舍五入只能判断正数一定正确,如果是负数就不一定了。
public class Demo { public static void main(String[] args) { System.out.println("-2.5="+Math.round(-2.5));System.out.println("-2.4="+Math.round(-2.4));System.out.println("-2.55="+Math.round(-2.55));System.out.println("-2.500001="+Math.round(-2.500001));System.out.println("-2.6="+Math.round(-2.6));System.out.println("-2.4="+Math.round(-2.4));System.out.println("-2.54="+Math.round(-2.54));System.out.println("2.511111="+Math.round(2.511111));System.out.println("2.5="+Math.round(2.5));System.out.println("2.4="+Math.round(2.4));}}输出:Math.round(-2.5)=-2Math.round(-2.4)=-2Math.round(-2.55)=-3Math.round(-2.500001)=-3Math.round(-2.6)=-3Math.round(-2.4)=-2Math.round(-2.54)=-3Math.round(2.511111)=3Math.round(2.5)=3Math.round(2.4)=2 是否还在为Ide开发工具频繁失效而烦恼,来吧关注以下公众号获取最新激活方式。亲测可用!
【正版授权,激活自己账号】:Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】:官方授权 正版激活 自己使用,支持Jetbrains家族下所有IDE…