Java_常用类11_BigInteger类

大数字

  a.    java.math.BigInteger:整数

  b.    java.math.BigDecimal:浮点数

1.    针对大整数的运算(BigInteger:可以让超过Integer范围内的数据进行运算)

2.    构造方法    

  A:BigInteger(String s)

public class BigIntegerDemo {
    public static void main(String[] args) {
        // 超过int范围内,Integer就不能再表示,所以就更谈不上计算了。
        Integer i = new Integer(100);
        System.out.println(i); // 100
        System.out.println(Integer.MAX_VALUE); // 2147483647
        Integer ii = new Integer("2147483647");
        System.out.println(ii); // 2147483647
        // Integer iii = new Integer("2147483648"); // NumberFormatException
        // System.out.println(iii);
        // 通过大整数来创建对象
        BigInteger bi = new BigInteger("2147483648");
        System.out.println("bi:" + bi); // bi:2147483648
    }
}

3.    成员方法(更多方法见API)

  A: public BigInteger add(BigInteger val):加

  B: public BigInteger subtract(BigInteger val):减

  C: public BigInteger multiply(BigInteger val):乘

  D: public BigInteger divide(BigInteger val):除

  E: public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组

public class BigIntegerDemo {
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("100");
        BigInteger bi2 = new BigInteger("50");
        System.out.println("add:" + bi1.add(bi2)); // add:150
        System.out.println("subtract:" + bi1.subtract(bi2)); // subtract:50
        System.out.println("multiply:" + bi1.multiply(bi2)); // multiply:5000
        System.out.println("divide:" + bi1.divide(bi2)); // divide:2
        BigInteger[] bis = bi1.divideAndRemainder(bi2);
        System.out.println("商:" + bis[0]); // 商:2
        System.out.println("余数:" + bis[1]); // 余数:0
    }
}

猜你喜欢

转载自www.cnblogs.com/zhaolanqi/p/9238734.html