Java基础:Math工具类全方位详解

Java基础:Math工具类全方位详解 简介本篇详细讲解java.lang.Math常用常量、取整、随机数、幂运算等API搭配实操代码适合新手收藏复习。一、概述java.lang.Math是Java自带数学工具类全部成员静态修饰无需new创建对象无需手动导包专门封装数学计算相关方法日常数值运算、随机数生成、几何计算、算法开发频繁使用。二、Math内置静态常量Math提供两个常用数学常量Math.PI圆周率πMath.E自然对数底数epublic class MathTest {public static void main(String[] args) {System.out.println(Math.PI);System.out.println(Math.E);}}三、核心常用API分类3.1 绝对值、最大值、最小值abs(数值)获取绝对值支持int、long、float、doublemax(a,b)获取两个数最大值min(a,b)获取两个数最小值System.out.println(Math.abs(-6.8));System.out.println(Math.max(15,32));System.out.println(Math.min(9,2));3.2 三种取整方式面试高频ceil()向上取整向数轴正方向取值floor()向下取整向数轴负方向取值round()四舍五入取整System.out.println(Math.ceil(2.1)); //3.0System.out.println(Math.floor(2.9));//2.0System.out.println(Math.round(2.5));//33.3 开方与幂运算sqrt(double)算术平方根pow(a,b)a的b次方System.out.println(Math.sqrt(64));System.out.println(Math.pow(3,2));//3²3.4 随机数 random()Math.random()返回[0.0,1.0)区间随机小数固定公式生成 [min,max] 整数(int)(Math.random()*(max-min1)min)//生成1~10随机整数int ran (int)(Math.random()*101);System.out.println(ran);3.5 三角函数参数为弧度System.out.println(Math.sin(Math.PI/2));//sin90°System.out.println(Math.cos(Math.PI)); //cos180°四、实战案例结合图形类求随机圆面积衔接上一篇Shape抽象类代码随机半径计算圆形面积//半径范围1~10double r (int)(Math.random()*101);double area Math.PI * Math.pow(r,2);System.out.println(半径r圆面积area);五、注意事项与总结Math所有方法都是static使用Math.方法名()double存在精度缺失金融高精度计算用BigDecimal随机数需求简单用Math.random()大量随机优先Random类。六、课后思考题可用于作业/自测题目1代码输出题public class Test{public static void main(String[] args){double num 4.39;System.out.println(Math.ceil(num));System.out.println(Math.floor(num));System.out.println(Math.round(num));}}思考打印结果分别是多少题目2编程题1使用Math方法随机生成5个[10,30]之间的整数遍历打印所有数字。题目3编程题2输入一个圆的随机半径范围2~15利用Math.PI和Math.pow计算周长与面积。题目4简答题Math中方法为什么不用实例化对象就能调用Math.random()取值范围是左闭右开还是全闭区间七、拓展后续更新Random随机类、BigDecimal高精度运算关注不迷路。