• java 18.数学工具类Math


    数学工具类Math

    java.lang.Math 类是数学相关的工具类,提供大量静态方法,完成与数学运算相关的操作,因为是lang包所以可以直接使用不需要导入。

    获取绝对值

    public static double abs(double num);
    

    向上取整

    public static double ceil(double num);
    

    向下取整

    public static double floor(double num);
    

    四舍五入,不带小数点

    public static double round(double num);
    

    PI圆周率常数

    public static final double PI = 3.14159265358979323846;
    

    其他

    使用(int) 10.99 强转(10),会舍弃所有小数位

    实例代码

    // 使用Arrays相关的api,将一个随机字符串中的所有字符升序排列,并倒序打印。
    public class demo001 {
        public static void main(String[] args) {
            System.out.println(Math.abs(0));  //0
            System.out.println(Math.abs(1));  //1
            System.out.println(Math.abs(-1));  //1
            System.out.println(Math.ceil(3.001));  //4.0
            System.out.println(Math.ceil(3.999));  //4.0
            System.out.println(Math.floor(3.001));  //3.0
            System.out.println(Math.floor(3.999));  //3.0
            System.out.println(Math.round(3.001));  //3
            System.out.println(Math.round(3.999));  //4
            System.out.println("-----------------------");
            System.out.println(Math.ceil(-3.001));  //-3.0
            System.out.println(Math.ceil(-3.999));  //-3.0
            System.out.println(Math.floor(-3.001));  //-4.0
            System.out.println(Math.floor(-3.999));  //-4.0
            System.out.println(Math.round(-3.001));  //-3
            System.out.println(Math.round(-3.999));  //-4
        }
    }
    

    细心的同学会发现,ceilfloor传入的参数如果有负号,那么函数实现的效果正好相反

    练习

    计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?

    // 计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
    public class demo001 {
        public static void main(String[] args) {
            int count = 0;
            double min = -10.8;
            double max = 5.9;
            for (int i = (int) min; i < max; i++) {
                int abs = Math.abs(i);
                if (abs > 6 || abs < 2.1) {
                    count++;
                }
            }
            System.out.println("总共有:" + count + "个!");
        }
    }
    

    这里记录一个出错点

    请添加图片描述

    我一开始想练下刚学的几个函数,

    通过abs取到绝对值10.8,再用floor向下取整10.0,然后再round拿掉小数点,得到10

    然后IDEA报红线了,一看round是返回long型的,int接不住,所以...

    但是不接收直接打印是OK的,可以得到期望的10

    更多学习笔记移步 https://www.cnblogs.com/kknote
  • 相关阅读:
    spring mvc 参数校验
    spring-boot 配置jsp
    java 多线程之取消与关闭
    spring transaction 初识
    java 读取环境变量和系统变量的方法
    每天一命令 git checkout
    每天一命令 git stash
    每天一命令 git reset
    log4j2配置详解
    专业名词及解释记录
  • 原文地址:https://www.cnblogs.com/kknote/p/15310904.html
Copyright © 2020-2023  润新知