java divide使用_Java Guava BigIntegerMath divide()用法及代码示例

Guava BigIntegerMath类的除法(BigInteger p,BigInteger q,RoundingMode模式)会返回p除以q的结果,并使用指定的RoundingMode进行舍入。

用法:

public static BigInteger divide(BigInteger p,

BigInteger q,

RoundingMode mode)

参数:此方法采用以下参数:

p:BigInteger股息

q:BigInteger除数

mode:用于计算p和q的除法的舍入模式。

返回值:此方法返回p除以q的结果,使用指定的RoundingMode进行舍入。

异常:如果q == 0或mode == UNNECESSARY并且a不是b的整数倍,则该方法引发ArithmeticException。

Enum RoundingMode

枚举常量

描述

CEILING

舍入模式向正无穷大舍入。

DOWN

舍入模式向零舍入。

FLOOR

舍入模式向负无穷大舍入。

HALF_DOWN

除非两个邻居等距,否则舍入模式将朝“nearest neighbor”舍入。

HALF_EVEN

舍入模式向“nearest neighbor”舍入,除非两个邻居都等距,在这种情况下,向偶数邻居舍入。

HALF_UP

除非两个邻居等距,否则舍入模式将朝“nearest neighbor”舍入。

UNNECESSARY

舍入模式可以断言所请求的操作具有准确的结果,因此不需要舍入。

UP

舍入模式从零舍入。

以下示例说明了BigIntegerMath.divide()方法:

范例1:

// Java code to show implementation of

// divide(BigInteger p, BigInteger q, RoundingMode mode)

// method of Guava's BigIntegerMath class

import java.math.*;

import com.google.common.math.BigIntegerMath;

class GFG {

// Driver code

public static void main(String args[])

{

BigInteger dividend1 = BigInteger.valueOf(55);

BigInteger divisor1 = BigInteger.valueOf(10);

// Using divide()

// method of Guava's BigIntegerMath class

BigInteger

quotient1

= BigIntegerMath

.divide(dividend1,

divisor1,

RoundingMode.HALF_DOWN);

System.out.println(dividend1 + " divided by "

+ divisor1

+ " with HALF_DOWN rounding mode:"

+ quotient1);

BigInteger dividend2 = BigInteger.valueOf(55);

BigInteger divisor2 = BigInteger.valueOf(10);

// Using divide()

// method of Guava's BigIntegerMath class

BigInteger

quotient2

= BigIntegerMath

.divide(dividend2,

divisor2,

RoundingMode.CEILING);

System.out.println(dividend2 + " divided by "

+ divisor2

+ " with CEILING rounding mode:"

+ quotient2);

}

}

输出:

55 divided by 10 with HALF_DOWN rounding mode:5

55 divided by 10 with CEILING rounding mode:6

范例2:

// Java code to show implementation of

// divide(BigInteger p, BigInteger q, RoundingMode mode)

// method of Guava's BigIntegerMath class

import java.math.*;

import com.google.common.math.BigIntegerMath;

class GFG {

// Driver code

public static void main(String args[])

{

try {

BigInteger dividend1 = BigInteger.valueOf(25);

BigInteger divisor1 = BigInteger.valueOf(0);

// Using divide()

// method of Guava's BigIntegerMath class

// This should raise "ArithmeticException"

// as divisor1 = 0

BigInteger

quotient1

= BigIntegerMath

.divide(dividend1,

divisor1,

RoundingMode.HALF_DOWN);

}

catch (Exception e) {

System.out.println("Exception:" + e);

}

}

}

输出:

Exception:java.lang.ArithmeticException:/ by zero

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值