Java number & Math 类
一般地,当需要使用数字的时候,我们通常使用内置数据类型,如: Byte 、int、long、double 等。
代码示例:
int a = 5000; Float b = 13.65f; byte c = 0x4a;
然而,在实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形。为了解决这个问题,Java 语言为每一个内置数据类型提供了对应的包装类。
所有的包装类 ( Integer 、Long、Byte、Double、Float、 short ) 都是抽象类 Number 的子类。
包装类 | 基本数据类型 |
boolean | boolean |
Byte | byte |
Short | short |
Integer | int |
Long | long |
char acter | char |
Float | float |
Double | double |
这种由编译器特别支持的包装称为装箱,所以当内置数据类型被当作对象使用的时候,编译器会把内置类型装箱为包装类。相似的,编译器也可以把一个对象拆箱为内置类型。 Number 类属于 java.lang 包。
代码示例:
public class test {
public static void main(String[] args) {
Integer x = 5;
x = x + 10;
System.out.println(x);
}
}
运行结果:
15
当 x 被赋为整型值时,由于x是一个对象,所以编译器要对x进行装箱。然后,为了使x能进行加运算,所以要对x进行拆箱。
Java Math 类
Java 的 Math 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、 平方根 和 三角函数 。
Math 的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用。
代码示例:
public class Test {
public static void main(String[] args) {
System.out.println("90 度的 正弦值 :" + Math.sin(Math.PI / 2));
System.out.println("0度的 余弦 值:" + Math.cos(0));
System.out.println("60度的 正切 值:" + Math.tan(Math.PI / 3));
System.out.println("1的反正切值: " + Math.atan(1));
System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI / 2));
System.out.println(Math.PI);
}
}
运行结果:
90 度的正弦值:1.0
0度的余弦值:1.0
60度的正切值:1.7320508075688767
1的反正切值: 0.7853981633974483
π/2的角度值:90.0
3.141592653589793
Number & Math 类方法
下面的表中列出的是 Number & Math 类常用的一些方法:
序号 | 方法与描述 |
1 | xxxValue() |
2 | compareTo() |
3 | equals() |
4 | valueOf() |
5 | toString () |
6 | parseInt () |
7 | abs () |
8 | ceil() |
9 | floor() |
10 | rint() |
11 | round() |
12 | min() |
13 | max() |
14 | exp() |
15 | log () |
16 | pow() |
17 | sqrt () |
18 | sin () |
19 | cos() |
20 | tan () |
21 | asin() |
22 | acos() |
23 | atan() |
24 | atan2() |
25 | toDegrees() |
26 | toRadians() |
27 | random () |
Math 的 floor,round 和 ceil 方法实例比较
参数 | Math.floor | Math.round | Math.ceil |
1.4 | 1 | 1 | 2 |
1.5 | 1 | 2 | 2 |
1.6 | 1 | 2 | 2 |
-1.4 | -2 | -1 | -1 |
-1.5 | -2 | -1 | -1 |
-1.6 | -2 | -2 | -1 |
floor,round 和 ceil 实例:
代码示例:
public class Main {
public static void main(String[] args) {
double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};
for (double num : nums) {
test(num);
}
}
private static void test(double num) {
System.out.println("Math.floor(" + num + ")=" + Math.floor(num));
System.out.println("Math.round(" + num + ")=" + Math.round(num));
System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));
}
}
运行结果:
Math.floor(1.4)=1.0
Math.round(1.4)=1
Math.ceil(1.4)=2.0
Math.floor(1.5)=1.0
Math.round(1.5)=2
Math.ceil(1.5)=2.0
Math.floor(1.6)=1.0
Math.round(1.6)=2
Math.ceil(1.6)=2.0
Math.floor(-1.4)=-2.0
Math.round(-1.4)=-1
Math.ceil(-1.4)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.6)=-2.0
Math.round(-1.6)=-2
Math.ceil(-1.6)=-1.0
下一期我们讲解Character类。