Java大数

BigInteger 类

import java.math.BigInteger; import java.util.Random; //表示整数 函数:

System.out.println(\构造两个BigInteger对象: \ //BigInteger(int numBits, Random rnd)

//构造一个随机生成的 BigInteger,它是在 0 到 (2^numBits - 1)(包括)范围内均匀分布的值 BigInteger bi1 = new BigInteger(55,new Random()); System.out.println(\ //BigInteger(byte[] val)

//将包含 BigInteger 的二进制补码表示形式的 byte 数组转换为 BigInteger。 BigInteger bi2 = new BigInteger(new byte[]{3,2,3}); System.out.println(\

//加 System.out.println(\ //减 System.out.println(\ //乘 System.out.println(\ //指数运算 System.out.println(\的2次方 = \ //整数商 System.out.println(\的整数商: \ //余数 System.out.println(\的余数: \ //整数商+余数 System.out.println(\ \ System.out.println(\ //比较大小,也可以用max()和min() if(bi1.compareTo(bi2) > 0)

System.out.println(\ else if(bi1.compareTo(bi2) == 0)

System.out.println(\ else if(bi1.compareTo(bi2) < 0)

System.out.println(\ //返回相反数 BigInteger bi3 = bi1.negate(); System.out.println(\的相反数: \ //返回绝对值 System.out.println(\的绝对值: \

import java.math.BigDecimal; //表示小数

Scanner cin=new Scanner(System.in);

System.out.println(\构造两个BigDecimal对象: \);

//用char[]数组创建BigDecimal对象,第二个参数为位移offset, //第三个参数指定长度

BigDecimal bd1 = new

BigDecimal(\.toCharArray(),2,15); System.out.println(\ + bd1); //用double类型创建BigDecimal对象

BigDecimal bd2 = new BigDecimal(134258767575867.0F); System.out.println(\ + bd2); //加

System.out.println(\ + bd1.add(bd2)); //减

System.out.println(\ + bd1.subtract(bd2)); //乘

System.out.println(\ + bd1.multiply(bd2)); //指数运算

System.out.println(\的2次方 = \ + bd1.pow(2)); //取商的整数部分

System.out.println(\的整数商: \ + bd1.divideToIntegralValue(bd2)); //返回余数计算

为:this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))

//System.out.println(bd1.subtract(bd1.divideToIntegralValue(bd2).multiply(bd2)));

System.out.println(\的余数: \ + bd1.remainder(bd2));

//取商和余,即bd1.divideToIntegralValue(bd2)与bd1.remainder(bd2)

System.out.println(\ + bd1.divideAndRemainder(bd2)[0] +

\ + bd1.divideAndRemainder(bd2)[1]); //比较大小,也可以用max()和min() if(bd1.compareTo(bd2) > 0)

System.out.println(\); elseif(bd1.compareTo(bd2) == 0)

System.out.println(\); elseif(bd1.compareTo(bd2) < 0)

System.out.println(\); //末位数据精度

System.out.println(\的末位数据精度: \ + bd1.ulp());

setScale(1)表示保留以为小数,默认用四舍五入方式

setScale(1,BigDecimal.ROUND_DOWN)直接删除多余的小数位,如2.35会变成2.3 setScale(1,BigDecimal.ROUND_UP)进位处理,2.35变成2.4

setScale(1,BigDecimal.ROUND_HALF_UP)四舍五入,2.35变成2.4

setScaler(1,BigDecimal.ROUND_HALF_DOWN),2.35变成2.3,即5向下舍 ROUND_HALF_UP: 遇到.5的情况时往上近似,例: 1.5 ->2

ROUND_HALF_DOWN : 遇到.5的情况时往下近似,例: 1.5 ->1

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4