Java 1.4 大数值问题

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

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

BigInteger a = BigInteger.valueOf(100); 

  但不能使用熟悉的算术运算符(如:+ 和 *) 处理大数值。 同时与 C++ 不同, Java 没有提供运算符重载功能。程序员无法重定义 + 和 * 运算 符, 使其应用于 BigInteger类的运算。所以,只能使用大数值类中方法。

java.util.Scanner5.0

• Biglnteger add(Biglnteger other)
• Biglnteger subtract(Biglnteger other)
• Biglnteger multiply(Biginteger other)
• Biglnteger divide(Biglnteger other)
• Biglnteger mod(Biglnteger other)
返回这个大整数和另一个大整数other的和、差、 积、 商以及余数。

• int compareTo(Biglnteger other)
如果这个大整数与另一个大整数 other 相等, 返回 0; 如果这个大整数小于另一个大整 数 other, 返回负数; 否则, 返回正数。

• static Biglnteger valueOf(long x)
返回值等于 x 的大整数。

java.math.Biglnteger 1.1

• BigDecimal add(BigDecimal other)
• BigDecimal subtract(BigDecimal other)
• BigDecimal multipiy(BigDecimal other)
• BigDecimal divide(BigDecimal other RoundingMode mode) 5.0
返回这个大实数与另一个大实数 other 的和、 差、 积、 商。要想计算商, 必须给出舍 入方式 (rounding mode)。RoundingMode.HALF UP 是在学校中学习的四舍五入方式 (BP, 数值 0 到 4 舍去, 数值 5 到 9 进位) 。它适用于常规的计算。有关其他的舍入方 式请参看 Apr文档。

• int compareTo(BigDecimal other)
如果这个大实数与另一个大实数相等, 返回 0 ; 如果这个大实数小于另一个大实数, 返回负数; 否则,返回正数。

• static BigDecimal valueOf(1ong x)
• static BigDecimal valueOf(1ong x,int scale)
返回值为 X 或 x / 10scale 的一个大实数。

猜你喜欢

转载自blog.csdn.net/weixin_45884316/article/details/107671820
1.4