答案是Math类提供基础数学运算方法,包括取整、绝对值、最大最小值、幂运算、平方根、随机数生成及三角函数等,所有方法均为静态,可直接调用。其中Math.round()实现四舍五入但负数需注意逻辑,Math.floor()向下取整,Math.ceil()向上取整,三者在处理负数时行为不同;通过Math.random()可生成[0.0,1.0)的随机数,结合公式可得指定范围内的随机整数;此外,Math类还支持科学计算如距离计算、角度转换等,广泛应用于几何、物理和游戏开发场景。

Java的
Math
Math.methodName()
说到
Math
首先是取整操作,这块儿稍微有点意思。
Math.round()
long
float
int
Math.round(3.5)
Math.round(3.4)
Math.round(-3.5)
floor(x + 0.5)
Math.floor()
double
Math.floor(3.9)
Math.floor(-3.1)
Math.ceil()
double
Math.ceil(3.1)
Math.ceil(-3.9)
接着是绝对值和最大最小值。
立即学习“Java免费学习笔记(深入)”;
Math.abs(x)
int
long
float
double
Math.max(a, b)
Math.min(a, b)
然后是幂运算和平方根。
Math.pow(base, exponent)
base
exponent
double
Math.pow(2, 3)
Math.sqrt(x)
double
Math.sqrt(9)
随机数生成,这个是很多场景的宠儿。
Math.random()
[0.0, 1.0)
double
还有一些科学计算会用到的:
Math.sin()
Math.cos()
Math.tan()
Math.toRadians()
Math.log()
Math.log10()
Math.PI
Math.E
实际用起来,这些方法虽然简单,但组合起来就能解决不少问题。比如,你可能需要计算两个点之间的欧几里得距离,那
Math.pow
Math.sqrt
Math.random
Math.round()
Math.floor()
Math.ceil()
这三个方法,初看都是取整,但骨子里逻辑完全不同,理解它们在正负数上的行为差异是关键。
Math.floor()
floor(3.9)
floor(3.1)
floor(-3.1)
Math.ceil()
ceil(3.1)
ceil(3.9)
ceil(-3.9)
ceil
Math.round()
floor(x + 0.5)
3.5
4
3.4
3
-3.5
floor(-3.5 + 0.5)
floor(-3.0)
-3
round
Math.random()
Math.random()
[0.0, 1.0)
double
[min, max]
min
max
一个常见的公式是:
int randomNum = (int)(Math.random() * (max - min + 1)) + min;
我们来拆解一下这个公式:
Math.random()
[0.0, 1.0)
double
(max - min + 1)
[1, 10]
10 - 1 + 1 = 10
Math.random() * (max - min + 1)
[0.0, 1.0)
[0.0, 范围长度)
[1, 10]
Math.random() * 10
[0.0, 10.0)
double
(int)(...)
int
[0, 范围长度 - 1]
[0.0, 10.0)
int
0, 1, ..., 9
+ min
min
[min, max]
[0, 9]
1
[1, 10]
举个例子,如果我想生成
[5, 15]
int min = 5;
int max = 15;
int randomNumber = (int)(Math.random() * (max - min + 1)) + min;
// 简化为: (int)(Math.random() * 11) + 5;
System.out.println("生成的随机数是:" + randomNumber);这样就能确保生成的数字在5到15之间,包括5和15。 虽然
Math.random()
java.util.Random
java.security.SecureRandom
Math
除了那些显而易见的加减乘除、求幂开方,
Math
一个常见的场景是处理角度和距离。比如,你可能需要计算两个地理坐标点之间的直线距离(虽然实际地球曲率要复杂得多,但简化模型下),或者在2D游戏中计算两个角色之间的距离。 这里
Math.pow()
Math.sqrt()
// 计算平面直角坐标系中两点 (x1, y1) 和 (x2, y2) 之间的距离 double x1 = 1.0, y1 = 1.0; double x2 = 4.0, y2 = 5.0; double distance = Math.sqrt(Math.pow(x
以上就是Java中Math类常用方法和技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号