Math工具类
java.lang.Math类是数学相关的工具类,里面提供了大量的方法,完成与数学运算有关的操作。
public static void main(String[] args) {
//java.lang.Math 构造方法是私有的,不让new
double pi=Math.PI;
System.out.println(Math.PI);//3.141592653589793
System.out.println(Math.random());
System.out.println(Math.round(1.3));//1
System.out.println(Math.round(1.6));//2
System.out.println(Math.floor(1.3));//1.0 地板 不要小数
System.out.println(Math.floor(1.6));//1.0
System.out.println(Math.ceil(1.3));//2.0 天花板 进位
System.out.println(Math.ceil(1.6));//2.0
System.out.println(Math.pow(2,3));//8 求平方 2的3次方
System.out.println(Math.max(10,20));//20
System.out.println(Math.min(10,20));//10
}
System.out.println(Math.random());//随机输出0~1的小数
//产生0~9的随机数
for (int i = 0; i < 9; i++) {
int num = (int) Math.round(Math.random() * (9 - 0) + 0);
System.out.printf("%d ", num);
}
System.out.println();
//编写程序,输出2021-07-01 0:0:0 到 now 之间的日期时间
for (int i = 0; i < 10; i++) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse("2021-07-1 0:0:0");
long start = d.getTime();
long now = System.currentTimeMillis();
long time = start + Math.round(Math.random() * (now - start));
System.out.println(sdf.format(time));
}
//随机 16进制颜色
int red=(int)Math.round(Math.random()*255);//返回值 long
int green=(int)Math.round(Math.random()*255);//返回值 long
int blue=(int)Math.round(Math.random()*255);//返回值 long
String color=String.format("#%02x%02x%02x",red,green,blue);
System.out.println(color);