Math.round(11.5)等於多少? Math.round(-11.5)等於多少?

来源:互联网 发布:C语言endif 编辑:程序博客网 时间:2024/04/28 05:06

Math.round(11.5)返回(long)12,Math.round(-11.5)返回(long)-11;

Math.round()方法是先将参数加上0.5然后去取它的Math.floor()值,Math.floor()可以获得一个数的整数部分,Math.floor求最大的整数但不大于本身而不是四舍五入

按照java中对round()的运算法则(long)Math.floor(a   +   0.5d),  
  当   -8.5<a<-8.0   如   a=   -8.4  
  则带入公式中   返回是    
  (long)Math.floor(-8.4   +   0.5d)  
  =(long)Math.floor(-7.9)  
  =-8  
  这个运算结果是对的,  
  当   a=-8.5   返回   (long)Math.floor(-8.0)=-8  
  当   -9<a<   -8.5   如a=-8.6   返回   (long)Math.floor(-8.1)=-9  
  这些结果从java中的运算逻辑看都是对的,至于和Excel中的运算结果不同应该是二者对round()方法有不同的定义  
所以round(-8.5)=floor(-8.0)=-8,而round(-8.6)=floor(-8.1)=-9;

System.out.println(-8.1   +   "   "   +   Math.round(-8.1));  
                  System.out.println(-8.2   +   "   "   +   Math.round(-8.2));  
                  System.out.println(-8.3   +   "   "   +   Math.round(-8.3));  
                  System.out.println(-8.4   +   "   "   +   Math.round(-8.4));  
                  System.out.println(-8.5   +   "   "   +   Math.round(-8.5));  
                  System.out.println(-8.6   +   "   "   +   Math.round(-8.6));  
                  System.out.println(-8.7   +   "   "   +   Math.round(-8.7));  
                  System.out.println(-8.8   +   "   "   +   Math.round(-8.8));  
                  System.out.println(-8.9   +   "   "   +   Math.round(-8.9));  
          }  
   
  运行结果:  
  -8.1   -8  
  -8.2   -8  
  -8.3   -8  
  -8.4   -8  
  -8.5   -8  
  -8.6   -9  
  -8.7   -9  
  -8.8   -9  
  -8.9   -9 

原创粉丝点击