蓝桥杯系列二:Java常用API-Math类

求最值

Math.min() 和 Math.max() 方法分别返回一个最小值和一个最大值

public class 求最值 {
    public static void main(String[] args) {
        //Math.min() 和 Math.max() 方法分别返回一个最小值和一个最大值
        int a = 10;
        int b = 20;
        System.out.println(Math.min(a, b));
        System.out.println(Math.max(a, b));
    }
}

运行结果:

10
20

求平方根

Math.sqrt(double a)//返回正确舍入的 double 值的正平方根

public class 求平方根 {
    public static void main(String[] args) {
        //Math.sqrt(double a)
        //返回正确舍入的 double 值的正平方根
        double a=100;
        System.out.println(Math.sqrt(a));
    }
}

运行结果:

10

求绝对值

Math.abs(参数类型 a)//返回一个类型和参数类型一致的绝对值

public class 求绝对值 {
    public static void main(String[] args) {
        int a = -10;
        System.out.println(Math.abs(a));    
    }
}

运行结果:

10

求幂

Math.pow(double a, double b)//注意无论是传入int还是long都会返回一个double类型的数。
注意返回的是double类型的数!

public class 求幂 {
    public static void main(String[] args) {
        int a=10;
        int b=5;
        int c= (int) Math.pow(10,5);//注意强制类型转换
        System.out.println(c);
    }
}

运行结果:

100000

得到一个随机数

Math.random()// 生成一个[0,1)之间的double类型的伪随机数
注意生成的是double类型的数!

public class 得到一个随机数 {
    public static void main(String[] args) {
        //为了得到一个[1, b] 之间的整数可以这样做:
        int a = (int)(Math.random()*b + 1); // [1, b]
    }
}

这里注意:

//重点:如果要得到[a, b]的一个整数则是
int a = (int)(Math.random()*(b - a + 1) + a)  
// + 1 是因为random()最大取不到1,所以上限取整后就会少1.

取整

Math.ceil(double x)//向上取整,返回大于该值的最近 double类型 值
Math.floor(double x)//向下取整,返回小于该值的最近 double类型值
Math.round(double x);//四舍五入取整

public class 取整 {
    public static void main(String[] args) {
        //Math.ceil(double x)
        //向上取整,返回大于该值的最近 double 值
        System.out.println(Math.ceil(1.4)); // 2.0
        System.out.println(Math.ceil(-1.6)); // -1.0

        //Math.floor(double x)
        //向下取整,返回小于该值的最近 double
        System.out.println(Math.floor(1.6)); // 1.0
        System.out.println(Math.floor(-1.6)); // -2.0

        //Math.round(double x);
        //四舍五入取整
        System.out.println(Math.round(1.1)); // 1
        System.out.println(Math.round(1.6)); // 2
        System.out.println(Math.round(-1.1)); // -1
        System.out.println(Math.round(-1.6)); // -2

    }
}

三角函数值

Math.cos(double a) 余弦
Math.acos(double a) 反余弦
Math.sin(double a) 正弦值
Math.asin(double a) 反正弦值
Math.tan(double a) 正切值
Math.atan(double a) 反正切
public class 三角函数 {
    public static void main(String[] args) {
        System.out.println(Math.cos(3.1415926));
    }
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值