栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中的大数是什么?怎么用?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中的大数是什么?怎么用?

概念

极少数特殊情况下,我们会感觉整数和浮点数的精度都不能满足我们的要求,这个时候我们需要使用到两个特殊的类:BigInteger和BigDecimal。这两个类对数据的精度处理很强大,可以处理任意包含长度数字序列的数值。BigInteger可以实现任意精度的整数运算,BigDecimal可以实现任意精度的浮点数运算。

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

BigInteger a = BigInteger.valueOf(100);

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

BigInteger reallyBig = new BigInteger("1521951919974948521591498614658741974141641519614974168416516114914196419");;

大数类还有一些常量:

BigInteger.ZERO, BigInteger.ONE, BigInteger.TWO, BigInteger.TEN

注意:我们不能使用我们常用的运算符(如+和-)处理大数,而需要使用大数类中的add和multiply方法

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

BigIntegerAPI

BigInteger add(BigInteger other)BigInteger subtract(BigInteger other)BigInteger multiply(BigInteger other)BigInteger divide(BigInteger other)BigInteger mod(BigInteger other)//返回这个大整数和另一个大整数other的和,差,积,商以及余数BigInteger sqrt()//得到这个BigInteger的平方根int compareTo(BigInteger other)//如果这个大整数与另一个大整数other相等,返回0;如果这个大整数小于另一个大整数other,返回负数;否则,返回正数static BigInteger ValueOf(long x)//返回值等于x的大整数

BigDecimalAPI

BigDecimal add(BigDecimal other)BigDecimal subtract(BigDecimal other)BigDecimal multiply(BigDecimal other)BigDecimal divide(BigDecimal other)BigDecimal divide(BigDecimal other, RoundingMode mode)int compareTo(BigDecimal other)//如果这个大实数与other相等,返回0;如果这个大实数小于other,返回附属;否则返回正数
static BigDecimal ValueOf(long x)static BigDecimal ValueOf(long x, int n)//返回值等于x或x/10ⁿ的一个大实数

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/967234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号