Java 中的 Math 类、Random 随机数、UUID、格式化字符串或数字、字符串和数字的相互转换、高精度计算、BigDecimal、计算机中的浮点数都是近似值
一、Math 类介绍:
(1) 简介
✏️ java.lang.Math 类提供了常见的数学计算功能
✏️ Math 类被 final 修饰(不能被继承)
✏️ Math 类不能被实例化
🍀 Math 类中都是 static 成员
🍀 Math 类不能被实例化,里面的非静态成员就毫无意义
(2) 属性
// 自然对数函数的底数(常量)
public static final double E = 2.7182818284590452354;
// π(圆周率)
public static final double PI = 3.14159265358979323846;
//刘徽开创了探索圆周率的精确方法。
//祖冲之在刘徽开创的探索圆周率的精确方法的基础上,首次将圆周率精算到小数点后第七位,即在3.1415926和3.1415927之间。
(3) 方法
① ceil 和 floor
public class TestDemo {
public static void main(String[] args) {
// 求绝对值: 666
// 正数的绝对值是其本身, 负数的绝对值是其相反数
System.out.println("求绝对值: " + Math.abs(-666));
// 求两个数的最大值: 777
System.out.println("求两个数的最大值: " + Math.max(666, 777));
// 求两个数的最小值: 2.36
System.out.println("求两个数的最小值: " + Math.min(3.14, 2.36));
}
}
🍀 max 方法可以求 int、long、float、double 等类型的两个数的最大值
🍀 体现了 Java 中的方法的重载特性
🍀 重载:① 方法名相同,参数类型或数量不同;② 重载与返回值类型、参数名称无关
🍀 Math 类中有很多重载的方法
public class TestDemo {
public static void main(String[] args) {
double n1 = 3.14159;
double n2 = -3.04159;
// 向下取整: 3.0
System.out.println("向下取整: " + Math.floor(n1));
// 向上取整: 4.0
System.out.println("向上取整: " + Math.ceil(n1));
// 向下取整: -4.0
System.out.println("向下取整: " + Math.floor(n2));
// 向上取整: -3.0
System.out.println("向上取整: " + Math.ceil(n2));
}
}
🍀 floor(地板):向下取整(最接近操作数的整数,并且要比操作数小)
🍀 ceil(天花板):向上取整(最接近操作数的整数,并且要比操作数大)
public class TestDemo {
public static void main(String[] args) {
double n1 = 3.44159;
double n2 = -3.54159;
// 四舍五入: 3
System.out.println("四舍五入: " + Math.round(n1));
// 四舍五入: -4
System.out.println("四舍五入: " + Math.round(n2));
}
}
②✏️ 书归正传,Knowledge is power. 中的 power 是力量或权力的意思,但在数学上也表示幂、次方
public class TestDemo {
public static void main(String[] args) {
// 2的3次方: 8.0
System.out.println("2的3次方: " + Math.pow(2, 3));
}
}
🍀 Math 类的 pow 方法用于求数的次方值,pow 就来自于power
③ sqrt
✏️ sqrt 是 Square Root 的简写,意思是:平方根
public class TestDemo {
public static void main(String[] args)</