大整数类BigInteger
支持无限大的整数运算
package mooc_8_01;
import java.math.BigInteger;
public class BigIntegerTest {
public static void main(String[] args) {
BigInteger b1 = new BigInteger("123456789");//声明Biginteger对象
BigInteger b2 = new BigInteger("987654321");//声明Biginteger对象
System.out.println("b1:" + b1 + ", b2:" + b2);
System.out.println("加法操作:" + b2.add(b1));//加法操作,对象间的加法采用函数,而不是函数
System.out.println("减法操作:" + b2.subtract(b1));
System.out.println("乘法操作:" + b2.multiply(b1));
System.out.println("除法操作:" + b2.divide(b1));
System.out.println("最大值" + b2.max(b1));
System.out.println("最小值" + b2.min(b1));
BigInteger result[] = b2.divideAndRemainder(b1);
System.out.println("商是:" + result[0] + ": 余数是:" + result[1]);
System.out.println("等价性是:" + b1.equals(b2));
int flag = b1.compareTo(b2);
if(flag == -1)
System.out.println("比较操作:b1<b2");
else if(flag == 0)
System.out.println("比较操作:b1==b2");
else
System.out.println("比较操作:b1>b2");
}
}
大浮点数BigDecimal
支持无限大的小数运算
注意精度和截断
package mooc_8_01;
import java.math.BigDecimal;
public class BigDecimalTest {
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("123456789.987654321");//声明BigDecimal对象,尽量采用字符串赋值,这样精度更准确.
BigDecimal b2 = new BigDecimal("123456789.987654321");//声明BigDecimal对象:
System.out.println("b1:" + b1 + ", b2:" + b2);
System.out.println("加法操作:" + b2.add(b1));//加法操作,对象间的加法采用函数,而不是函数
System.out.println("减法操作:" + b2.subtract(b1));
System.out.println("乘法操作:" + b2.multiply(b1));
System.out.println("除法操作:" + b2.divide(b1,10,BigDecimal.ROUND_HALF_UP));//需要指定位数,防止无限循环;
System.out.println("最大值" + b2.max(b1));
System.out.println("最小值" + b2.min(b1));
int flag = b1.compareTo(b2);
if(flag == -1)
System.out.println("比较操作:b1<b2");
else if(flag == 0)
System.out.println("比较操作:b1==b2");
else
System.out.println("比较操作:b1>b2");
}
}