美文网首页Java学习
Java中Math.round方法的讨论

Java中Math.round方法的讨论

作者: FFJ | 来源:发表于2017-09-11 22:45 被阅读4次
    public class Hello {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("Math.round(-11.5):" + Math.round(-11.5));
            System.out.println("Math.round(-11.50001):" + Math.round(-11.50001));
            System.out.println("Math.round(11.5):" + Math.round(11.5));
            System.out.println("Math.round(-11.4):" + Math.round(-11.4));
            System.out.println("Math.round(11.4):" + Math.round(11.4));
            System.out.println("Math.round(-11.6):" + Math.round(-11.6));
            System.out.println("Math.round(11.6):" + Math.round(11.6));
    //      int f = Math.round(-11.5);
    //      byte d = Math.round(-11.5f);
        }
    }
    
    运行结果:
    Math.round(-11.5):-11
    Math.round(-11.50001):-12
    Math.round(11.5):12
    Math.round(-11.4):-11
    Math.round(11.4):11
    Math.round(-11.6):-12
    Math.round(11.6):12
    
    1. Math.round()方法是用来求四舍五入的。由上面运行结果的对比来看,除了负数有0.5(如-11.5)的情况外,其余的都是数的绝对值四舍五入,再加上相对应的正负号。
      System.out.println("Math.round(-11.5):" + Math.round(-11.5));的结果来看(也即所有类似-x.5形式的值),Math.round()方法是偏向于向正无穷方向的。
    2. 对于程序中的int f = Math.round(-11.5);,eclipse提示“Type mismatch: cannot convert from long to int”,所以Math.round()方法默认返回long类型的数。而对于byte d = Math.round(-11.5f);,eclipse则提示“Type mismatch: cannot convert from int to byte”,所以把Math.round()方法里的表达式强制类型转换为float类型的数据,返回值的类型就变成了int型。

    相关文章

      网友评论

        本文标题:Java中Math.round方法的讨论

        本文链接:https://www.haomeiwen.com/subject/wolqsxtx.html