Java 大数

如果基本的整数和浮点数精度不能够满足需求,看到给的数大于10^18, 那么可以使用java.math 包中的两个很有用的类:Biglnteger 和 BigDecimaL 这两个类可以处理包含任意长度数字序列的数值。

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

1. java.math.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; 如果这个大整数小于另一个大整 数 other, 返回负数; 否则, 返回正数。
• static Biglnteger valueOf(long x) 返回值等于 x 的大整数。 (静态函数valueOf的参数只能是long类型的)

BigInteger(String val);            将指定字符串转换为十进制表示形式;

BigInteger(String val,int radix);           将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger

例题

求两个数的差

import java.math.BigInteger;
import java.util.Scanner;
public class Main{
 public static void main(String[] args)  {
	 Scanner sc=new Scanner(System.in);
	BigInteger a=sc.nextBigInteger();
	BigInteger b=sc.nextBigInteger();
	System.out.println(a.subtract(b));
	
}
}

2.java.math.BigDecimal

基本上和整数的一样

• BigDecimal divide(BigDecimal other RoundingMode mode)

要想计算商, 必须给出舍入方式 。RoundingMode.HALF_UP 一种方式 (BP, 数值 0 到 4 舍去, 数值 5 到 9 进位) 。

static BigDecimal valueOf(long x)
• static BigDecimal valueOf(double x)
• static BigDecimal valueOf(long x,int scale)    
返回值为 x 或 x / 10scale 的一个大实数。

关于舍入方式参考:点我
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值