我想对于Math类大家一定很熟悉了,是Java提供的一个用来进行简单数学运算的工具类。对于Math类来说,常用的方法有:
- 加法
-
public static int addExact(int x, int y);求两个int类型整数的和
-
public static long addExact(long x, long y):求两个long类型整型数的和
加法的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 加法
System.out.println("3 + 4 = " + Math.addExact(3, 4));
System.out.println("5L + 4L = " + Math.addExact(5L, 4L));
}
}
执行结果如下图所示:
- 减法
-
public static int subtractExact(int x, int y):求两个int类型整数的差
-
public static long subtractExact(long x, long y):求两个long类型整数的差
减法的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 减法
System.out.println("6 - 4 = " + Math.subtractExact(6, 4));
System.out.println("7L - 2L = " + Math.subtractExact(7L, 2L));
}
}
执行结果如下图所示:
- 乘法
-
public static int multiplyExact(int x, int y):求两个int类型整数的积
-
public static long multiplyExact(long x, int y):求一个long类型整型数和一个int类型整数的积
-
public static long multiplyExact(long x, long y):求两个long类型整型数的积
乘法的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 乘法
System.out.println("6 * 4 = " + Math.multiplyExact(6, 4));
System.out.println("7L * 2 = " + Math.multiplyExact(7L, 2));
System.out.println("7L * 5L = " + Math.multiplyExact(7L, 5L));
}
}
执行结果如下图所示:
- 除法
-
public static int floorDiv(int x, int y):求两个int类型整数的相除的结果
-
public static long floorDiv(long x, int y):求一个long类型整型数除以一个int类型整数的结果
-
public static long floorDiv(long x, long y):求两个long类型整型数相除的结果
除法的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 除法
System.out.println("6 / 4 = " + Math.floorDiv(6, 4));
System.out.println("7L / 2 = " + Math.floorDiv(7L, 2));
System.out.println("7L / 5L = " + Math.floorDiv(7L, 5L));
}
}
执行结果如下图所示:
- 求余
-
public static int floorMod(int x, int y):求两个int类型整数的取模
-
public static int floorMod(long x, int y):求一个long类型整型数对另一个int类型整数的取模
-
public static long floorMod(long x, long y):求两个long类型整型数的取模
求余的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 求余
System.out.println("6 % 4 = " + Math.floorMod(6, 4));
System.out.println("7L % 2 = " + Math.floorMod(7L, 2));
System.out.println("7L % 5L = " + Math.floorMod(7L, 5L));
}
}
执行结果如下图所示:
- 取反
-
public static int negateExact(int a):对一个int类型的整数进行取反
-
public static long negateExact(long a):对一个long类型的整数进行取反
取反的示例代码如下所示:
public class MathTest {
public static void main(String[] args) {
// 取反
System.out.println("3取反的结果为:" + Math.negateExact(3));
System.out.println("-5L取反的结果为:" + Math.negateExact(-5L));
}
}