java中的数学工具类Math(round方法是重点)

数学工具类Math

1. 概述

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

2. 基本的方法

public static double abs(double num);获取绝对值。有多种重载,absolutely绝对地
public static double ceil(double num);向上取整,ceil是天花板的意思
public static double floor(double num);向下取整,floor是地板的意思
public static long round(double num);四舍六入五成双(看下面代码的注释),round有大约,完整的意思

3. 四种方法一起通过代码演示一遍

public class MathMethod {
    public static void main(String[] args) {
        //abs方法,取绝对值
        System.out.println(Math.abs(3.14)); //3.14
        System.out.println(Math.abs(0));    //0
        System.out.println(Math.abs(-2.2)); //2.2

        System.out.println("---------------------");

        //ceil方法,向上取整,往大的靠
        System.out.println(Math.ceil(3.2));  //4.0
        System.out.println(Math.ceil(3.8));  //4.0
        System.out.println(Math.ceil(-3.2)); //-3.0
        System.out.println(Math.ceil(-3.8)); //-3.0

        System.out.println("---------------------");
        
        //floor方法,向下取整,往小的靠
        System.out.println(Math.floor(3.2));  //3.0
        System.out.println(Math.floor(3.8));  //3.0
        System.out.println(Math.floor(-3.2)); //-4.0
        System.out.println(Math.floor(-3.8)); //-4.0

        System.out.println("---------------------");

        //【注意,面试高频】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
        System.out.println(Math.floor(-2.5 + 0.5));  //与Math.round(-2.5)结果一致

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

4. 圆周率Math.PI

在Math类的源码中,我们可以看到,它自定义的圆周率 PI = 3.14159265358979323846

以后的计算如果需要用到PI,尽量用已经定义好的圆周率,非常精确

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值