java学习-Math

用于数值取整

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);

运行结果:
在这里插入图片描述

发布了107 篇原创文章 · 获赞 10 · 访问量 9677

猜你喜欢

转载自blog.csdn.net/liying15/article/details/102691929
今日推荐