java如何使用大数值

如何基本的整数和浮点数精度不能满足大数值的要求,可以使用java.math包里的BigInteger和BigDecimal类。

BigInteger类实现了任意精度的整数运算。BigDecimal实现了任意精度的浮点数计算。

使用静态的方法valueOf()可以把数值转化为大数值,如:BigInteger a=BigInteger.valueOf(10);

我们无法使用+和*,取而代之的是add和multiply方法。

BigInteger c=a.add(b);

BigInteger d=c.multiply(b.add(BigInteger.valueOf(2)));

 

import java.math.*;
import java.util.*;
class BigInteger
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

System.out.println("how many numbers do you need to draw?");
int k=in.nextInt();

System.out.println("what is your highest number you can draw?");
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.println(lotteryodds);

}
}

posted @ 2013-09-03 19:26  一叶落香  阅读(440)  评论(0编辑  收藏  举报