Java 使用StrictMath subtractExact()的示例
在Java中,subtractExact()是StrictMath类的静态方法。它在‘java.lang’包中可用。
在本文中,我们将讨论StrictMath和其一些内置方法。我们还将看到subtractExact()方法的实现以及它与该类的其他方法的区别。
Java中的StrictMath类
StrictMath是一个继承自Object类的最终类。我们可以使用它的方法而无需创建实例,因为该类的所有方法都是静态方法,我们可以在没有对象的情况下调用静态方法。
调用静态方法
Class_name.static_method_name
导入StrictMath类
import java.lang.StrictMath;
首先让我们讨论StrictMath类的几种方法,然后在下一部分中我们来讨论它的subtractExact()方法。
- abs( value ) - 返回给定参数的正值。它只接受一个参数。
-
ceil( value ) - 以double值作为参数,返回大于给定参数的四舍五入值。
-
floor( value ) - 以double值作为参数,返回小于给定参数的四舍五入值。
-
log( value ) - 以double值作为参数,返回以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("Printing a random value between 0 and 1: " + StrictMath.random());
System.out.println("Ceil value of d2: " + StrictMath.ceil(d2));
System.out.println("Absolute value of d1: " + StrictMath.abs(d1));
System.out.println("Floor value of d2: " + StrictMath.floor(d2));
System.out.println("Floor modulus value of n1 and n2: " + StrictMath.floorMod(n1, n2));
System.out.println("Logarithmic value of d2: " + StrictMath.log(d2));
System.out.println("Maximum value between n1 and n2: " + StrictMath.max(n1, n2));
System.out.println("Minimum value between n1 and n2: " + StrictMath.min(n1, n2));
System.out.println(" 9 to power 2 is: " + StrictMath.pow(n2, 2));
System.out.println("Rounded value of d1: " + StrictMath.round(d1));
}
}
输出
Printing a random value between 0 and 1: 0.5155915867224573
Ceil value of d2: 35.0
Absolute value of d1: 46.992
Floor value of d2: 34.0
Floor modulus value of n1 and n2: 0
Logarithmic value of d2: 3.5342703358865175
Maximum value between n1 and n2: 45
Minimum value between n1 and n2: 9
9 to power 2 is: 81.0
Rounded value of 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("Difference between i1 and i2: " + StrictMath.subtractExact(i1, i2));
}
}
输出
Difference between i1 and 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("Difference between l1 and l2: " + StrictMath.subtractExact(l1, l2));
}
}
输出
Difference between l1 and l2: 171720024
结论
当我们需要进行数学计算时,StrictMath类非常有用。它提供了许多内建方法来执行数字数据类型的操作。在本文中,我们了解了StrictMath类及其内建方法subtractExact()。