详述 Java 语言中的大数值

来源:互联网 发布:嵌入式linux终端 编辑:程序博客网 时间:2024/05/20 02:50

1 简介

在基本的整数和浮点数精度不能给满足我们的需求的时候,我们就可以使用 java.math 包中的两个非常有用的类:BigInteger 和 BigDecimal。这两个类可以处理任意长度数字序列的数值。BigInteger 类实现了任意精度的整数运算,BigDecimal 类实现了任意精度的浮点数运算。

2 大数值

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

BigInteger bi = BigInteger.valueOf(215);

遗憾的是,在使用大数值的时候,不用够使用咱们熟悉的算数运算符,包括:加、减、乘、除等。但是,大数值为我们提供了对应的方法,如 add(表示加法)和 multiply(表示乘法)等。

BigInteger b1 = bi.add(b2);  // b1 = bi + b2BigInteger b1 = b2.multiply(BigInteger.valueOf(215));  // b1 = b2 * 215

3 API

/*** 下面的方法都来自:java.math.BigInteger 包*/BigInteger add(BigInteger other)BigInteger subtract(BigInteger other)BigInteger multiply(BigInteger other)BigInteger divide(BigInteger other)BigInteger mod(BigInteger other)/* 返回这个大整数和另一个大整数 other 的和、差、积、商以及余数 */int compareTo(BigInteger other)/* 如果这个大整数与另一个大整数 other 相等,返回 0;如果这个大整数小于另一个大整数 other,返回负数;否则,返回正数 */static BigInteger valueOf(long x)/* 返回值等于 x 的大整数 */BigDecimal add(BigDecimal other)BigDecimal subtract(BigDecimal other)BigDecimal multiply(BigDecimal other)BigDecimal divide(BigDecimal other)/* 返回这个大实数和另一个大实数 other 的和、差、积、商。在此,需要注意的是:想要计算商,必须给出舍入方式,例如  RoundingModel.HALF_UP */int compareTo(BigDecimal other)/* 如果这个大实数与另一个大实数 other 相等,返回 0;如果这个大实数小于另一个大实数 other,返回负数;否则,返回正数 */static BigDecimal valueOf(long x)static BigDecimal valueOf(long x, int scale)/* 返回值等于 x 或者 x/10^(scale) 的大实数 */

4 代码示例

import java.math.BigInteger;import java.util.Scanner;/** * @author 维C果糖 * @create 2017-02-15 */public class ExOfBigValue {    /**     * 模拟彩票中奖的概率     */    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.println("请输入您的幸运数字:");        int k = sc.nextInt();        System.out.println("请输入您能想到的最大整数:");        int n = sc.nextInt();        /**         * 计算的二项式系数为:n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)         */        BigInteger bi = BigInteger.valueOf(1);        for (int i = 1; i <= k ; i++) {            bi = bi.multiply(BigInteger.valueOf(n - i + 1)).divide(BigInteger.valueOf(i));        }        System.out.println("您中奖的概率是 1/" + bi + ",祝您好运!");    }}
1 0
原创粉丝点击