Java BigInteger divide()方法及示例
java.math.BigInteger .divide(BigInteger val) 用于计算两个BigIntegers的除法。BigInteger类内部使用整数数组进行处理,对BigIntegers对象的操作不如对基数的操作快。该方法对当前的BigInteger进行操作,该方法被调用,BigInteger作为参数被传递。
语法
public BigInteger divide(BigInteger val)
参数: 本方法接受一个参数val,它是除以这个BigInteger的值。
返回值: 该方法返回一个BigInteger,其中包含整数除法(this / val)(非浮点值),也就是说,它将结果四舍五入到其下限值。
异常: 参数val不能是0,否则会抛出算术异常。
下面的程序用来说明BigInteger的divide()方法。
例1:
// Java program to demonstrate
// divide() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// BigInteger object to store result
BigInteger div;
// Two objects of String created
// Holds the values to calculate the division
String input1 = "400000000000000000"
+ "000000000000000000";
String input2 = "8000000";
// Convert the string input to BigInteger
BigInteger a
= new BigInteger(input1);
BigInteger b
= new BigInteger(input2);
// Using divide() method
div = a.divide(b);
// Display the result in BigInteger
System.out.println("The division of\n"
+ a + " \nby\n" + b + " "
+ "\nis\n" + div);
}
}
输出。
The division of
400000000000000000000000000000000000
by
8000000
is
50000000000000000000000000000
例2:展示它是如何舍弃结果的
// Java program to demonstrate
// divide() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// BigInteger object to store result
BigInteger div;
// Two objects of String created
// Holds the values to calculate the division
String input1 = "456216545";
String input2 = "21255132";
// Convert the string input to BigInteger
BigInteger a
= new BigInteger(input1);
BigInteger b
= new BigInteger(input2);
// Using divide() method
div = a.divide(b);
// Display the result in BigInteger
System.out.println("The division of\n"
+ a + " \nby\n" + b + " "
+ "\nis " + div);
double d = Double.parseDouble(input1)
/ Double.parseDouble(input2);
// Display result in double type
// To match both the results
System.out.print("Using double result is " + d);
}
}
输出。
The division of
456216545
by
21255132
is 21
Using double result is 21.46383024109189
例3:演示除以0时抛出的异常。
// Java program to demonstrate
// divide() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// BigInteger object to store result
BigInteger div;
// Two objects of String created
// Holds the values to calculate the division
String input1 = "456216545"
+ "452133155";
String input2 = "0";
// Convert the string input to BigInteger
BigInteger a
= new BigInteger(input1);
BigInteger b
= new BigInteger(input2);
// Using divide() method
try {
div = a.divide(b);
// Display the result in BigInteger
System.out.println("The division of\n"
+ a + " \nby\n" + b + " "
+ "\nis\n" + div + "\n");
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
}
输出。
java.lang.ArithmeticException: BigInteger divide by zero
参考: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#divide(java.math.BigInteger).