java.math包中的两个类BigInteger和BigDecimal可以处理任意长度数字序列的数值,其中BigInteger类实现了任意精度整数运算
方法 | 描述 |
---|---|
Biglnteger add(Biglnteger other) | + |
Biglnteger subtract(Biglnteger other) | - |
Biglnteger multipiy(Biginteger other) | * |
Biglnteger divide(Biglnteger other) | / |
Biglnteger mod(Biglnteger other) | % |
int compareTo(Biglnteger other) | 比较大整数,相等返回0... |
static Biglnteger valueOf(1ong x) | 返回等于x的大整数 |
实例:简单计算彩票中奖概率
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("输入数据量:");
int k = in.nextInt();
System.out.print("输入最大数值:");
int n = in.nextInt();
/**
* 计算公式:n*(n-1)*(n-2)...*(n-k+1)/(1*2*3...*k)
*/
BigInteger data = BigInteger.valueOf(1);
for(int i = 1; i <= k; i++){
data = data.multiply(BigInteger.valueOf(n - i + 1)).divide(BigInteger.valueOf(i));
}
System.out.println("您的赔率为 1 / " + data);
}
实验结果:
输入数据量:899
输入最大数值:1000
您的赔率为 1 /568964957759154625871570891364554919337986243806613847511466679201702369260156552020087890263543860444430482482575263148691415762587708401000
BigInteger类实现了任意精度浮点数运算
方法 | 描述 |
---|---|
BigDecimal add(BigDecimal other) | 的 |
BigDecimal subtract(BigDecimal other) | |
BigDecimal multipiy(BigDecimal other) | |
BigDecimal divide(BigDecimal other RoundingMode mode) 5.0 | 返回这个大实数与另一个大实数other 的和、差、积、商。要想计算商, 必须给出舍入方式( rounding mode) |
int compareTo(BigDecimal other) | 如果这个大实数与另一个大实数相等, 返回0 ; 如果这个大实数小于另一个大实数,返回负数; 否则,返回正数。 |
static BigDecimal valueOf(1ong x) | |
static BigDecimal valueOf(1 ong x ,int scale) | 返回值为X 或x / 10scale 的一个大实数 |
原文:https://www.cnblogs.com/code-duck/p/13226829.html