Java核心技术卷I知识点总结四

一、大数

如果基本的整数和浮点精度不能够满足需求,那么可以使用Java.math包中两个很有用的类:BigIntegerBigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算,BigDecimal实现任意精度的浮点数运算。

使用静态的valueOf方法可以将普通的数值转换为大数:

BigInteger a = BigInteger.valueOf(100);

对于更大的数可以使用一个带字符串参数的构造器:

BigInteger reallyBig = new BigInteger("6465448966545646846546546546465454654654987987564654646546546");

另外还有一些常量:BigInteger.ZEROBigInteger.ONEBigInteger.TEN,Java9之后还增加了BigInteger.TWO

大数运算不能使用人们熟悉的算术运算符(如:+和*)处理大数。而需要使用大数类中的add和multiply方法。

BigInteger c = a.add(b);//c = a+b;
BigInteger d = c.multiplay(b.add(BigInteger.valueOf(2)));//d = c*(b+2);

java.math.BigInteger API

BigInteger add(BigInteger other)相加
BigInteger subtract(BigInteger  other)相减
BigInteger multiply(BigInteger  other)相乘
BigInteger divide(BigInteger  other)相除
BigInteger mod(BigInteger  other)取余
BigInteger sqrt()    java 9平方
int compareTo(BigInteger other)

如果这个大整数与另一个大整数other相等返回0,如果这个大整数小于另一个大整数other返回负数,否则返回正数

static BigInteger valueOf(long x)返回等于的大整数

java.math.BigDecimal API

BigDecimal add(BigDecimal other)相加
BigDecimal subtract(BigDecimal other)相减
BigDecimal multiply(BigDecimal other)相乘
BigDecimal divide(BigDecimal other)相除
BigDecimal divide(BigDecimal  other,RoundingMode mode) 如果商是个无限循环小数,第一个divide方法会抛出一个异常。要得到一个四舍五入的结果就需要使用本方法。参数RoundingMode代表四舍五入的方式
int compareTo(BigDecimal  other)

如果这个大实数与另一个大实数other相等返回0,如果这个大实数小于另一个大实数other返回负数,否则返回正数

static BigDecimal  valueOf(long x)返回等于的大整数
static BigDecimal  valueOf(long x,int scale)返回值等于x或x/n<sup>2</sup>

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值