Math类中的方法
本次学习的方法有
-
绝对值(Math.abs)
-
向上取整(Math.ceil) 向下取整(Math.floor)
-
0…1之间的随机数(Math.random()) //*多少就是在0…多少之间
-
取几位小数 两个方法
-1.乘100后向下取整,再除100
-2.DecimalFormat 类实现,这个类会四舍五入 -
随机数的类(Random) 调用.nextInt(52)方法,即可得到0…51之间的随机数
-
平方(Math.pow(a,b)) //a的b次方
-
开方(Math.sqrt)
-
两数的最大值和最小值(Math.max和Math.min)
public class MathDemo {
public static void main(String[] args) {
//绝对值
System.out.println(Math.abs(-2)); //2
//向上取整 Math.ceil(12.3f)->13.0
System.out.println((int)Math.ceil(12.3f)); //13
//0.。1之间的随机小数 到不了1
System.out.println(Math.random()); //0..1.0 double
//取两位小数 (Math.floor向下取整)
//方法1:
double d=3.1456d;
System.out.println(Math.floor(d*100)/100); //3.14
//方法2:
DecimalFormat df=new DecimalFormat("#.##");
//df DecimalFormat 第三位四舍五入
System.out.println(df.format(d)); //3.15
//随机数的类
Random rd=new Random();
System.out.println(rd.nextInt(52)); //0..51
//2的3次方
System.out.println(Math.pow(2,3)); //8.0
//开方
System.out.println(Math.sqrt(64)); //8.0
//max最大值 min最小值
int a=13,b=14,c=15;
System.out.println(Math.max((Math.max(a,b)),c)); //15
}
}