Math类
Math类
概述
java.util.Math 包含了用于执行基本数学运算的方法,如指数,幂次方,对数,平方根等。里面的方法均是静态方法,并且也不需要创建对象,调用起来很方便
基本运算的方法
1.public static double abs(doubel a)
返回double值的绝对值 abs–absolute
double d1=Math.abs(-5.3);//5.3
double d2=Math.abs(5.3);//5.3
double d3=Math.abs(0.0);//0.0
2.public static double ceil(double a)
返回大于等于参数的最小整数,向上取整
double d1=Math.ceil(5.3);//6.0
double d2=Math.ceil(5.9);//6.0
double d3=Math.ceil(-5.3);//-5.0
3.public static double floor(double a)
返回小于等于参数的最大整数,往下取整
double d1=Math.floor(5.9);//5.0
double d2=Math.floor(5.1);//5.0
double d3=Math.floor(-5.9);//-6.0
4.public static long round(double a)
返回最接近参数的long类型
long l1=Math.round(5.5);// 6
long l2=Math.round(5.4);// 5
long l3=Math.round(-5.5);//-5 5舍6入
long l4=Math.round(-5.6);//-6
练习:使用Math相关API方法计算出-10.8到5.9之间绝对值大于6或者小于2.1的整数有多少个?分别是
public static void main(String[] args){
double max=5.9;
double min=-10.8;
int count=0;
for(double i=Math.ceil(min);i<=Math.ceil(max);i++){
if(Math.abs[i]>6 || Math.abs[i]<2.1){
count++;
System.out.print((int)i+" ");
}
}
System.out.println();
System.out.println(count);
}
-10 -9 -8 -7 -2 -1 0 1 2
9
版权声明:本文为zwh19990526原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。