用于数值取整
public class StuMath {
public static void main(String[] args){
System.out.println("Math.ceil(1.1)="+Math.ceil(1.1)); //向上取整
System.out.println("Math.floor(1.9)="+Math.floor(1.9)); //向下取整
System.out.println("Math.round(1.4)="+Math.round(1.4)); //四舍五入
System.out.println("Math.round(1.5)="+Math.round(1.5));//四舍五入
}
}
运行结果如下:
其中round的返回值类型是long
ceil和floor的返回值是double
取随机数
System.out.println("随机生成一个[0,1)之间的浮点数"+Math.random());
System.out.println("随机生成一个[0,3]之间的整数"+(int)(Math.random()*4));
System.out.println("随机生成一个[5,9]之间的整数"+(5+(int)(Math.random()*5)));
String[] optLit = {"电信","联通","移动","广电"};
String optName = optLit[(int)(Math.random()*4)];
System.out.println("随机取数组中的一个值:"+optName);
运行结果: