在日常处理数据时总会涉及到数据的计算,但是在java中有些运算符甚至是专用符号,有些呢则是识别不了,而java官方提供了很多关于数学计算的API方法,且都是静态的,可以直接通过类名调用,下面列几个常用的API方法
- static E abs (E e): 此处E只能指double、float、int、long 四种数据类型且与返回值类型保持一致 作用是返回E类型的绝对值
示例代码:
public static void main(String[] args) {
int num1 = Math.abs(-3);
System.out.println(num1);
float num2 = Math.abs(- 0.3f);
System.out.println(num2);
double num3 = Math.abs(- 3.5);
System.out.println(num3);
long num4 = Math.abs(-4354l);
System.out.println(num4);
}
结果展示:
- static E max(E e1, E e2): 此处E只能指double、float、int、long四种数据类型且两个数据的数据类型和返回值类型需保持一致,作用是返回两个数中较大的数
示例代码:
public static void main(String[] args) {
System.out.println(Math.max(3, 4));// int型
System.out.println(Math.max(1.2f, 2.0f));// float型
System.out.println(Math.max(4.5d, 2.5d));// double型
System.out.println(Math.max(432l, 532l));// long型
}
结果展示:
- static E min(E e1, E e2): 此处E只能指double、float、int、long四种数据类型且两个数据的数据类型和返回值类型需保持一致,作用是返回两个数中较小的数
示例代码:
public static void main(String[] args) {
System.out.println(Math.min(3, 4));// int型
System.out.println(Math.min(1.2f, 2.0f));// float型
System.out.println(Math.min(4.5d, 2.5d));// double型
System.out.println(Math.min(432l, 532l));// long型
}
结果展示:
- static double pow(double b1, double b2): 作用是返回b1的b2次幂值
示例代码:
public static void main(String[] args) {
System.out.println(Math.pow(2,3));// 求2的3次方
// 注意:返回的值是double类型
}
结果展示:
- static long round(double e): 作用是返回最接近参数的long类型值(符合四舍五入) 向上取整
示例代码:
public static void main(String[] args) {
System.out.println(Math.round(4.4d));// double类型值取整
System.out.println(Math.round(4.5d));
}
结果展示:
- static int round(float e): 作用是返回最接近参数的int类型值(符合四舍五入)向上取整
示例代码:
public static void main(String[] args) {
System.out.println(Math.round(1.4f));// float类型值取整
System.out.println(Math.round(-4.5f));
}
结果展示:
- static double sqrt(double b): 返回正确舍入的double值的正平方根
示例代码:
public static void main(String[] args) {
System.out.println(Math.sqrt(4.0));
System.out.println(Math.sqrt(6));
// 注意:参数数据类型和返回值数据类型都是double
}
结果展示:
- static double random(): 返回一个[0 , 1.0) 之间的伪随机double值
示例代码:
public static void main(String[] args) {
System.out.println(Math.random());// 返回[0,1.0)
System.out.println(Math.random());
System.out.println(Math.random());
System.out.println(Math.random());
}
结果展示: