作者:zgshenxz_474 | 来源:互联网 | 2023-06-12 20:45
Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算的相关操作publicstaticdoubleobs(doublenum); 获取绝对值,有多种重载。publ
Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算的相关操作
public static double obs(double num); 获取绝对值,有多种重载。
public sttaic double ceil(double num); 向上取整
public sttaic double floor(double num); 向下取整
public sttaic long round(double num); 四舍五入
Math.PI 代表近似圆周率的常量(double)
public static void main(String[] args) {
//获取绝对值
System.out.println(Math.abs(11.56));
System.out.println(Math.abs(0));
System.out.println(Math.abs(-11.56));
System.out.println("=============");
//向上取整
System.out.println(Math.ceil(3.5));
System.out.println(Math.ceil(3.1));
System.out.println(Math.ceil(0));
System.out.println("=============");
//向下取整
System.out.println(Math.floor(3.9));
System.out.println(Math.floor(3.1));
System.out.println(Math.floor(0));
System.out.println("=============");
//四舍五入
System.out.println(Math.round(3.5));
System.out.println(Math.round(3.4));
//PI
System.out.println(Math.PI);
}
运行结果:
练习
计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
public static void main(String[] args) {
int count = 0;
double min = -10.8;
double max = 5.9;
for (int i = (int) min; i ) {
int abs = Math.abs(i);
if (abs>6 || abs<2.1){
System.out.println(i);
count++;
}
}
System.out.println("共有:"+count+"个");
}运行结果: