如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中两个很有用的类:BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算,BigDecimal实现任意精度的浮点数运算。
使用静态的valueof方法可以将普通的数值转换为大数:
BigInteger a = BigInteger.valueOf(100);对于更大的数,可以使用一个带字符串参数的构造器:
BigInteger reallyBig = new BigInteger("134443493494321591498614658741974141641519614974168416516114914196419");另外还有一些常量:BigInteger.ZERO、BigInteger.ONE和BigInteger.TEN
注意:我们不能使用算术运算符(如:+和*)处理大数,而需要使用大叔类中的add和multiply方法。
BigInteger c = a.add(b); //c = a + bBigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); //d = c * (b + 2)案例
假设你被邀请参加抽奖活动,并从500个可能的数值中抽取60个,下面程序会告诉你中彩的概率是多少
import java.math.BigInteger;import java.util.Scanner;/** * @author JKC * @Description: * @date 2022/6/29 09:42 */public class SixSample { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("你需抽多少次?"); int k = in.nextInt(); System.out.println("你能抽的最高数是什么?"); int n = in.nextInt(); BigInteger lotteryOdds = BigInteger.valueOf(1); for (int i = 1; i <= k; i++) { lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1).divide(BigInteger.valueOf(i))); } System.out.printf("你的概率在%d分之一", lotteryOdds); }}
java.math.BigInteger API
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的大整数
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)返回这个大实数与other的和,差,积。如果商是个无限循环小数,第一个divide方法会抛出一个异常。要得到一个舍入的结果,就要使用第二个方法。RoundingMode.HALF_UP是指四舍五入方式。int compareTo(BigDecimal other)如果这个大实数与other相等,返回0;如果这个大实数小于other,返回附属;否则返回正数static BigDecimal ValueOf(long x)static BigDecimal ValueOf(long x, int n)返回值等于x或x/10?的一个大实数