Math类的使用简单介绍

本文介绍了Java中Math类的一些核心方法,包括求幂运算`pow()`, 向上取整`ceil()`, 向下取整`floor()`, 生成随机数`random()`, 求最小值`min()`和最大值`max()`,以及平方根`sqrt()`和立方根`cbrt()`等。通过实例展示了这些方法的用法,适合初学者学习和巩固。
摘要由CSDN通过智能技术生成
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);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值