Java数学工具类Math的Math.round()方法

导读:本篇文章讲解 Java数学工具类Math的Math.round()方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Java数学工具类Math的Math.round()方法

1.概述

java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。

round() 方法返回一个最接近的 int、long 型值,四舍五入。

round 表示”四舍五入”,**算法为Math.floor(x+0.5)**即将原来的数字加上 0.5 后再向下取整所以 Math.round(11.5) 的结果为 12,Math.round(-11.5) 的结果为 -11。

2.语法

该方法有以下几种语法格式:

  • long round(double d)
  • int round(float f)

3.参数

  • d – double 或 float 的原生数据类型
  • f – float 原生数据类型

4.记忆口诀和代码案例

public static long round(double num);四舍六入五成双(看下面代码的注释),round有大约,完整的意思

public class MathMethod {
    public static void main(String[] args) {
        //【注意,面试高频】round方法,四舍 六入 五成双
        //先看看四舍六入,如果出现负数,先转成正数,再四舍六入,最后加上负号
        System.out.println(Math.round(3.4));//3
        System.out.println(Math.round(3.6));//4
        System.out.println(Math.round(-3.4));//-3
        System.out.println(Math.round(-3.6));//-4

        //五成双是什么意思呢?当出现0.5结尾的时候,就给它再加上+0.5,5不就成双了,接着再对相加的结果进行floor运算
        System.out.println(Math.round(-2.5));//-2
        /**public static double floor(double num);向下取整,floor是地板的意思
         * floor方法,向下取整,往小的靠*/
        System.out.println(Math.floor(-2.5 + 0.5)); //-2.0 与Math.round(-2.5)结果一致

        System.out.println(Math.round(2.5)); //3
        System.out.println(Math.floor(2.5 + 0.5)); //3.0 与Math.round(2.5)结果一致
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/85604.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!