1. 程式人生 > >math類和biginteger類

math類和biginteger類

array max 1.0 new 調用 向上取整 最小 pri ceil

Math類:這種工具類,一般不會創建對象,方法為靜態方法,直接調用

package com.oracle.demo02;

public class MathDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //絕對值
        System.out.println(Math.abs(-99));
        //向上取整
        System.out.println(Math.ceil(12.2));
        //向下取整
        System.out.println(Math.floor(12.2));
        
//取最大值 System.out.println(Math.max(111,333)); //取最小值 System.out.println(Math.min(111,333)); //取次冪 System.out.println(Math.pow(2,3)); //取隨機數 System.out.println(Math.random()); //四舍五入 System.out.println(Math.round(12.2)); //π System.out.println(Math.PI); } }

Array類:操作數組的一些方法

package com.oracle.demo02;

import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        method1();
        
        
    }
    public static void method(){
        int[] arr = {3,6,9,11,15};
        //返回指定值對應的索引值(數組必須有序)
        //如果不存在,索引值=(-當前索引-1)
int i = Arrays.binarySearch(arr, 6); System.out.println(i); } public static void method1(){ int[] arr = {5,7,1,3,2,9,}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // for(int i:arr){ // System.out.print(i); // } } }

BigInteger類:比long類型的數據還大的值

package com.oracle.demo02;

import java.math.BigInteger;

public class BigDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        method();
    }
    public static void method(){
        BigInteger bi =new BigInteger("100000000000000000000000000000000000000000");
        BigInteger bi2 = new BigInteger("20000000000000000000000000000000000000000");
        //加法
        System.out.println(bi.add(bi2));
        //減法
        System.out.println(bi.subtract(bi2));
        //乘法
        System.out.println(bi.multiply(bi2));
        //除法
        System.out.println(bi.divide(bi2));
    }
}

BigDecimal類:避免精度損失的

package com.oracle.demo02;

import java.math.BigDecimal;

public class BigDemo01 {
    public static void main(String[] args) {
        method3();
    }
    public static void method(){
        BigDecimal bd1 = new BigDecimal("0.09");
        BigDecimal bd2 = new BigDecimal("0.01");
        System.out.println(bd1.add(bd2));
    }
    public static void method1(){
        BigDecimal bd1 = new BigDecimal("1.0");
        BigDecimal bd2 = new BigDecimal("0.31");
        System.out.println(bd1.subtract(bd2));
    }
    public static void method2(){
        BigDecimal bd1 = new BigDecimal("1.015");
        BigDecimal bd2 = new BigDecimal("100");
        System.out.println(bd1.multiply(bd2));
    }
    public static void method3(){
        BigDecimal bd1 = new BigDecimal("1.301");
        BigDecimal bd2 = new BigDecimal("100");
        System.out.println(bd1.divide(bd2,BigDecimal.ROUND_FLOOR,3));
    }
}

註意 在除法運算的時候要用divide()方法的參數類型來進行小數位數的控制

math類和biginteger類