Math类的使用简单介绍

import static java.lang.Math.*;

public class MathDemo {
    
    
    public static void main(String[] args) {
    
    

        //1.求x的y次方幂pow(x,y)
        double pow = pow(2, 8);
        System.out.println("pow(2,8) = " + pow);

        //2.向上取整 ceil(x)
        double x = ceil(-2.3);
        double y = ceil(0);
        double z = ceil(+2.3);
        System.out.println("ceil(-2.3) = " + x); // -2.0
        System.out.println("ceil(0) = " + y); // 0.0
        System.out.println("ceil(+2.3) = " + z); // 3.0
        int totalRecords = 107;
        final int PAGE_SIZE = 10;
        int pageCount = (int)Math.ceil(totalRecords * 1.0 / PAGE_SIZE); // 11
        System.out.println("总共107条记录,每页显示10条记录,共" + pageCount + "页");

        //3.向下取整 floor(x)
        x = floor(-2.3);
        y = floor(0);
        z = floor(+2.3);
        System.out.println("floor(-2.3) = " + x); // -3.0
        System.out.println("floor(0) = " + y); // 0.0
        System.out.println("floor(+2.3) = " + z); // 2.0

        //4.随机数 random() 返回[0.0~1.0)随机double数
        double random = Math.random();
        System.out.println("Math.random() = " + random);
        //随机产生[50~100]区间随机整数
        //产生指定区间的随机整数公式:  (int)((Math.random() * (最大值-最小值 + 1)) + 最小值)
        int count = 0;
        for (int i = 0; i < 50; i++) {
    
    
            int number = (int)((Math.random() * (100- 50 + 1)) + 50);
            System.out.print(number + "\t");
            if((i+1) % 10 == 0) {
    
    
                System.out.println();
            }
        }

        //5.返回两个参数中的最小值 min(a,b)
        int min = (int)Math.min(10.0, 20.0);
        System.out.println("Math.min(10.0, 20.0) = " + min);

        //6.返回两个参数中的最大值 max(a,b)
        int max = (int)Math.max(10.0, 20.0);
        System.out.println("Math.max(10.0, 20.0) = " + max);

        //7.取a的平方根sqrt(a)
        double sqrt = sqrt(9.0);
        System.out.println("sqrt(9.0) = " + sqrt);

        //8.取a的立方根  Math.cbrt(a)
        double cbrt = cbrt(8.0);
        System.out.println("cbrt(8.0) = " + cbrt);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44125965/article/details/126872973