关于Math.round()方法分析

(3) 2024-05-15 12:23

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说关于Math.round()方法分析,希望能够帮助你!!!。

Math.round()方法是四舍五入,原理是在原数的基础上加0.5,然后向下取整(非常重要),如果进行判断只是记住了四舍五入很多情况下是错误的,下面进行分析

  1. Math.round(-2.5),四舍五入之后是-3,你或许说前面有负号,应该是-2,那么Math.round(-2.4)多少呢?是不是就应该是-3了,Math.round(-2.6)是多少呢?-2吧。
    这都是有错误的结果,如果是四舍五入取进行判断,正数没有任何问题,但是如果是负数就不确定了。

  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

  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)=-2
Math.round(-2.4)=-2
Math.round(-2.55)=-3
Math.round(-2.500001)=-3
Math.round(-2.6)=-3
Math.round(-2.4)=-2
Math.round(-2.54)=-3
Math.round(2.511111)=3
Math.round(2.5)=3
Math.round(2.4)=2


今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复