• Java中的Math类、Array类、大数据运算


    Math类:数学类

    概念:

      Math类是包含用于执行基本数学运算的方法的数学工具类,如初等指数、对数、平方根和三角函数。其所有方法均为静态方法,并且一般不会创建对象。

    常用方法:

        //求绝对值
        System.out.println(Math.abs(-9));
        //向上取整
        System.out.println(Math.ceil(12.2));
        //向下取整
        System.out.println(Math.floor(12.9));
            //求两数最大值
        System.out.println(Math.max(12.9, 12.0));
        //求两数最小值
        System.out.println(Math.min(12.9, 12.0));
        //求a的b次方
        System.out.println(Math.pow(2, 10));
            //求0-1之间的随机小数
        System.out.println(Math.random());
        //四舍五入
        System.out.println(Math.round(12.6));

    Array类:数组

    概念:

      此类包含用来操作数组(比如排序和搜索)的各种方法。需要注意,如果指定数组引用为 null,则访问此类中的方法都会抛出空指针异常NullPointerException

    常用方法:

    sort方法,用来对指定数组中的元素进行升序排序(元素值从小到大进行排序)

    //arr数组元素{1,5,9,3,7}, 进行排序后arr数组元素为{1,3,5,7,9}
    int[] arr = {1,5,9,3,7};
    Arrays.sort( arr );

     toString方法,用来返回指定数组元素内容的字符串形式

    int[] arr = {1,5,9,3,7};
    String str = Arrays.toString(arr); // str的值为[1, 3, 5, 7, 9]

     binarySearch方法,在指定数组中,查找给定元素值出现的位置。若没有查询到,返回位置为-(这个值应该在的位置)-1。(-下标-1)要求该数组必须是个有序的数组。

    int[] arr = {1,3,4,5,6};
    int index = Arrays.binarySearch(arr, 4); //index的值为2
    int index2= Arrasy.binarySearch(arr, 2); //index2的值为-2

    大数据运算:

    BigInteger:

      java中long型为最大整数类型,对于超过long型的数据如何去表示呢.在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigInteger对象.在BigInteger类中,实现四则运算都是方法来实现,并不是采用运算符。

    部分方法:

    public static void main(String[] args) {
            //大数据封装为BigInteger对象
              BigInteger big1 = new BigInteger("12345678909876543210");
              BigInteger big2 = new BigInteger("98765432101234567890");
              //add实现加法运算
              BigInteger bigAdd = big1.add(big2);
              //subtract实现减法运算
              BigInteger bigSub = big1.subtract(big2);
              //multiply实现乘法运算
              BigInteger bigMul = big1.multiply(big2);
              //divide实现除法运算
              BigInteger bigDiv = big2.divide(big1);
    }

    BigDecimal类:

      double和float类型在运算中很容易丢失精度(计算机是二进制的,在计算时会丢失精度),造成数据的不准确性,Java提供我们BigDecimal类可以实现浮点数据的高精度运算。

      

  • 相关阅读:
    Mac配置docker阿里云加速器
    Docker初学笔记
    Mac下载安装Tomcat
    MySQL
    monkey
    Git基本使用
    yaml语法
    PAT_B数素数 (20)
    PAT_B1002数字分类
    PAT基础编程练习
  • 原文地址:https://www.cnblogs.com/heitaitou/p/12849571.html
Copyright © 2020-2023  润新知