如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中的两个很有用的类:BigInteger和BigDecimal。
BigInteger类实现了任意精度的整数运算
BigDecimal实现了任何精度的浮点数运算
使用静态的valueof()方法可以将普通数值转换为大数值(BigInteger a = BigInteger.valueOf(100);)
遗憾的是,不能使用人们熟悉的算术运算符(如:+和*)使用大数值,而需要使用大数值类中的add和multiply方法
import java.math.*;
import java.util.*;
/**
* This program uses big numbers to compute the odds of winning the grand prize in a lottery.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class BigIntegerTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();
/*
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
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.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}
}