java.lang.Math.subtractExact()是java中的内置数学函数,该函数返回参数的差值。不需要。
用法:
public static int subtractExact(int a, int b)
参数:
a:the first value
b:the second value to be subtracted from the first
返回:
This method returns the difference of the arguments .
Exception:
It throws ArithmeticException - if the result overflows an int
例:展示java.lang.Math.subtractExact()方法的用法。
// Java program to demonstrate working
// of java.lang.Math.subtractExact() method
import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
int a = 300;
int b = 200;
System.out.println(Math.subtractExact(a, b));
}
}
输出:
100
// Java program to demonstrate working
// of java.lang.Math.subtractExact() method
import java.lang.Math;
class Gfg2 {
// driver code
public static void main(String args[])
{
int x = Integer.MIN_VALUE;
int y = 10;
System.out.println(Math.subtractExact(x, y));
}
}
输出:
Runtime Error:
Exception in thread "main" java.lang.ArithmeticException:integer overflow
at java.lang.Math.subtractExact(Math.java:829)
at Gfg2.main(File.java:13)