大数的两个库BigInteger,BigDecimal。分别是大整数和大实数(具体有多大不详)。 操作: 1. 包含:import java.math.*; 2. 申请: 单个元素:BigInteger a, b; BigDecimal a, b; 数组: BigInteger a[]; a = new BigInteger[1024]; BigDecimal a[]; a = new BigDecimal[1024]; 3. 赋值: a[1] = BigDecimal.valueOf(1); a[1] = BigInteger.valueOf(1); 4. 加减乘除: BigInteger a, b; a = BigInteger.valueOf(1); b = BigInteger.valueOf(2); System.out.println(a.add(b)); System.out.println(a.subtract(b)); System.out.println(a.multiply(b)); System.out.println(a.divide(b));
BigDecimal a, b; a = BigDecimal.valueOf(5); b = BigDecimal.valueOf(3); System.out.println(a.add(b)); System.out.println(a.subtract(b)); System.out.println(a.multiply(b)); System.out.println(a.divide(BigDecimal.valueOf(1))); //这里要整除,否则会RE System.out.println(a.divide(b, 4, 4)); //这里不太明白第3个参数是什么意思 System.out.println(a.divide(b, 4, BigDecimal.ROUND_HALF_UP)); //这里第二个参数是保留位数,第三个参数是进位方式。 5. 比较大小: BigDecimal a, b; a = BigDecimal.valueOf(5); b = BigDecimal.valueOf(3); if(a.compareTo(b) > 0) System.out.println("a is greater than b"); else if(a.compareTo(b) == 0) System.out.println("a is equal to b"); else if(a.compareTo(b) < 0) System.out.println("a is lower than b"); |