Java大数字运算(BigInteger类和BigDecimal类)

要使用 BigInteger 类,首先要创建一个 BigInteger 对象。BigInteger 类提供了很多种构造方法,其中最直接的一种是参数以字符串形式代表要处理的数字。这个方法语法格式如下:

  BigInteger(String val)

这里的 val 是数字十进制的字符串。例如,要将数字 5 转换为 BigInteger 对象,语句如下:

  BigInteger bi = new BigInteger("5")

 

 BigInteger类的常用运算方法
方法名称说明
add(BigInteger val) 做加法运算
subtract(BigInteger val) 做减法运算
multiply(BigInteger val) 做乘法运算
divide(BigInteger val) 做除法运算
remainder(BigInteger val) 做取余数运算
divideAndRemainder(BigInteger val) 做除法运算,返回数组的第一个值为商,第二个值为余数
pow(int exponent) 做参数的 exponent 次方运算
negate() 取相反数
shiftLeft(int n) 将数字左移 n 位,如果 n 为负数,则做右移操作
shiftRight(int n) 将数字右移 n 位,如果 n 为负数,则做左移操作
and(BigInteger val) 做与运算
or(BigInteger val) 做或运算
compareTo(BigInteger val) 做数字的比较运算
equals(Object obj) 当参数 obj 是 Biglnteger 类型的数字并且数值相等时返回 true, 其他返回 false
min(BigInteger val) 返回较小的数值
max(BigInteger val) 返回较大的数值

 

import java.math.BigInteger;
import java.util.Scanner;

public class Test09 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个整型数字:");
        // 保存用户输入的数字
        int num = input.nextInt();

        // 使用输入的数字创建BigInteger对象
        BigInteger bi = new BigInteger(num + "");

        // 计算大数字加上99的结果
        System.out.println("加法操作结果:" + bi.add(new BigInteger("99")));

        // 计算大数字减去25的结果
        System.out.println("减法操作结果:" + bi.subtract(new BigInteger("25")));

        // 计算大数字乘以3的结果
        System.out.println("乘法橾作结果:" + bi.multiply(new BigInteger("3")));

        // 计算大数字除以2的结果
        System.out.println("除法操作结果:" + bi.divide(new BigInteger("2")));

        // 计算大数字除以3的商
        System.out.println("取商操作结果:" + bi.divideAndRemainder(new BigInteger("3"))[0]);

        // 计算大数字除以3的余数
        System.out.println("取余操作结果:" + bi.divideAndRemainder(new BigInteger("3"))[1]);

        // 计算大数字的2次方
        System.out.println("取 2 次方操作结果:" + bi.pow(2));

        // 计算大数字的相反数
        System.out.println("取相反数操作结果:" + bi.negate());
    }
}

 

posted @ 2023-01-11 10:49  6NULL9  阅读(47)  评论(0编辑  收藏  举报