总体方法一览

image-20220831122742832

abs

返回绝对值

有如下几个重载形式:

public static int abs(int a)

public static long abs(long a)

public static float abs(float a)

public static double abs(double a)

1
2
3
4
5
6
7
8
9
10
11
12
13
// int
System.out.println(Math.abs(-1));
// long
System.out.println(Math.abs(-4L));
// float
System.out.println(Math.abs(-4.9F));
// double
System.out.println(Math.abs(-9.0));
// 输出结果
// 1
// 4
// 4.9
// 9.0

pow

求幂函数

public static double pow(double a, double b)

返回值为ab

1
2
3
// 求2的3次方
System.out.println(Math.pow(2, 3));
// 输出结果:8.0

ceil

向上取整

public static double ceil(double a)

1
2
3
// 4.0向上取整
System.out.println(Math.ceil(3.6));
// 输出结果:4.0

floor

向下取整

public static double floor(double a)

1
2
3
// 6.8向下取整
System.out.println(Math.floor(6.8));
// 输出结果:6.0

round

四舍五入

有两个重载形式

public static long round(double a)

public static int round(float a)

1
2
3
4
5
6
7
// 5.6四舍五入
System.out.println(Math.round(5.6));
// 5.1F四舍五入
System.out.println(Math.round(5.1F));
// 输出结果:
// 6
// 5

sqrt

求开方

public static double sqrt(double a)

1
2
3
// 9开方
System.out.println(Math.sqrt(9));
// 输出结果:3.0

max

求两个数的最大值

有四种重载形式

public static int max(int a, int b)

public static long max(long a, long b)

public static float max(float a, float b)

public static double max(double a, double b)

1
2
3
4
5
6
7
8
9
10
11
12
13
// int
System.out.println(Math.max(3, 9));
// long
System.out.println(Math.max(3L, 9L));
// float
System.out.println(Math.max(3.0F, 9.0F));
// double
System.out.println(Math.max(3.0, 9.0));
// 输出结果
// 9
// 9
// 9.0
// 9.0

min

求两个数的最小值

有四种重载形式

public static int min(int a, int b)

public static long min(long a, long b)

public static float min(float a, float b)

public static double min(double a, double b)

1
2
3
4
5
6
7
8
9
10
11
12
13
// int
System.out.println(Math.min(3, 9));
// long
System.out.println(Math.min(3L, 9L));
// float
System.out.println(Math.min(3.0F, 9.0F));
// double
System.out.println(Math.min(3.0, 9.0));
// 输出结果
// 3
// 3
// 3.0
// 3.0

random

求随机数

public static double random()

这个方法返回值为[0,1)的小数

求[a, b)范围的随机数:a + Math.random() * (b - a + 1)

1
2
3
4
5
6
7
8
9
// 随机输出一个随机数
System.out.println(Math.random());
// 随机输出3个值在[100, 200)的数
for (int i = 0; i < 3; i++) {
System.out.print(100 + Math.random() * (200 - 100 + 1) + " ");
}
// 输出结果
// 0.26838755803089587
// 122.50889918535731 193.98736178448462 139.2267529280548