Java 中的 StrictMath subtractExact() 示例
在 Java 中,subtractExact() 是 StrictMath 类的静态方法。它在"java.lang"包中可用。
在本文中,我们将讨论 StrictMath 及其一些内置方法。我们还将看到 subtractExact() 方法的实现以及它与此类的其他方法有何不同。
Java 中的 StrictMath 类
StrictMath 是一个扩展对象类的最终类。我们可以使用它的方法而无需创建实例,因为此类的所有方法都是静态的,我们可以在没有对象的情况下调用静态方法。
调用静态方法
Class_name.static_method_name
导入 StrictMath 类
import java.lang.StrictMath;
我们先讨论一下 StrictMath 类的几个方法,然后在下一节讨论它的 subtractExact() 方法。
abs( value ) − 返回给定参数的正值。它仅接受一个参数。
ceil( value ) − 它以双精度值作为参数,并返回大于给定参数的四舍五入值。
floor( value ) − 它以双精度值作为参数,并返回小于给定参数的四舍五入值。
log( value ) − 它接受双精度值并返回以 e 为底的对数值。
max(value1, value2) − 返回给定两个参数中的最大值。
min(value1, value2) − 返回给定两个参数中的最小值。
random( value ) − 它生成一个介于 0 到 1 之间的随机数。
pow(value1, value2) − 它接受两个参数并返回 value1 的 value2 次幂。
round( value ) − 它返回给定参数的最接近的整数值。
示例
在此示例中,我们将实现上面讨论的方法以便我们更好地理解。我们使用类名来调用所有这些方法。
import java.lang.StrictMath; public class Methods { public static void main(String[] args) { int n1 = 45; int n2 = 9; double d1 = 46.992; double d2 = 34.27; System.out.println("打印 0 到 1 之间的随机值:" + StrictMath.random()); System.out.println("d2 的上限值:" + StrictMath.ceil(d2)); System.out.println("d1 的绝对值:" + StrictMath.abs(d1)); System.out.println("d2 的下限值:" + StrictMath.floor(d2)); System.out.println("n1 和 n2 的下限模数值:" + StrictMath.floorMod(n1, n2)); System.out.println("d2 的对数值:" + StrictMath.log(d2)); System.out.println("n1 和 n2 之间的最大值:" + StrictMath.max(n1, n2)); System.out.println("n1 和 n2 之间的最小值:" + StrictMath.min(n1, n2)); System.out.println(" 9 的 2 次方为:" + StrictMath.pow(n2, 2)); System.out.println("d1 的四舍五入值:" + StrictMath.round(d1)); } }
输出
打印 0 到 1 之间的随机值:0.5155915867224573 d2 的上限值:35.0 d1 的绝对值:46.992 d2 的下限值:34.0 n1 和 n2 的下限模数值:0 d2 的对数值:3.5342703358865175 n1 和 n2 之间的最大值:45 n1 和 n2 之间的最小值:9 9 的 2 次方为:81.0 d1 的舍入值:47
subtractExact() 方法
subtractExact() 方法计算两个给定参数之间的差值并返回该差值。它适用于整数和长整型原始数据类型。
到目前为止,我们讨论的所有方法都不会引发任何类型的异常。但是,当结果超出其参数的类型范围时,它会引发 ArithmeticException。
语法
StrictMath.strictExact(val1, val2);
它将从"val1"中减去"val2"。
示例 1
以下示例说明了使用整数数据类型实现 subtractExact() 方法。
import java.lang.StrictMath; public class Methods { public static void main(String[] args) { int i1 = 45; int i2 = 9; System.out.println("i1 和 i2 之间的差异:" + StrictMath.subtractExact(i1, i2)); } }
输出
i1 和 i2 之间的差异:36
示例 2
在此示例中,我们将看到它与长数据类型一起工作。
import java.lang.StrictMath; public class Methods { public static void main(String[] args) { long l1 = 459653499; long l2 = 287933475; System.out.println("l1 和 l2 之间的差异:" + StrictMath.subtractExact(l1, l2)); } }
输出
l1 和 l2 之间的差异:171720024
结论
当我们需要进行数学计算时,StrictMath 类非常有用。它提供了多种内置方法来对数值数据类型执行操作。在本文中,我们了解了 StrictMath 类及其内置方法 subtractExact()。