Java中Math.round方法的讨论

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型。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,778评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制?答:可以有多个类,但只能有一个publ...
    岳小川阅读 970评论 0 2
  • 下面的内容是对网上原有的Java面试题集及答案进行了全面修订之后给出的负责任的题目和答案,原来的题目中有很多重复题...
    独念白阅读 1,391评论 0 3
  • 一、技术分析在这首练习中,右手的弹法与第12首基本相似,只是小连线和跳音的弹法更多些。本首中出现了一个新的技术内容...
    ibluebox阅读 1,081评论 0 0