Math的用法

java.lang.Math类,数学工具类,提供大量静态方法简化数学操作

一、常用字段

public static final double E = 2.7182818284590452354; // 自然数e
public static final double PI = 3.14159265358979323846; // 圆周率π

二、常用方法

1、public static int min(int a, int b),最小值

​   public static int max(int a, int b),最大值

  		int min = Math.min(100, 200);      // 100
        double max = Math.max(12.6, 15.8); // 15.8

2、public static int abs(int a),绝对值

 		int abs1 = Math.abs(-106);    // 106
        double abs2 = Math.abs(12.6); // 12.6

3、public static double ceil(double a),向上取整

​   public static double floor(double a),向下取整

		// 向上取整 数轴正方向
        double d1 = Math.ceil(15.2);  //  16.0
        double d2 = Math.ceil(-15.2); // -15.0

        // 向下取整 数轴负方向
        double d3 = Math.floor(15.0);  //  15.0
        double d4 = Math.floor(-15.2); // -16.0
  • 向上取整:车子一次运送10个箱子,现在有21个箱子,需要运送几趟
  • 向下取整:超市里总共花费1024.24元,抹掉小数部分,付款1024.00元

4、public static int round(float a),四舍五入

​   public static long round(double a)

如果 a 是非负数,小数大于等于0.5入,小于0.5舍

如果 a 是负数,小数大于0.5入,小于等于0.5舍弃

		int i = Math.round(12.3F); // 12
        long l = Math.round(12.9); // 13
		System.out.println(Math.round(-15.50));  // -15
        System.out.println(Math.round(-15.501)); // -16

5、public static double pow(double a, double b),幂运算

		// 返回第一个参数的第二个参数次幂的值
		double d1 = Math.pow(3, 3);  // 27.0
        double d2 = Math.pow(2, -1); // 0.5

6、public static double sqrt(double a),平方根

		// 如果参数为 NaN 或小于 0,那么结果为 NaN
        double d1 = Math.sqrt(16.0); // 4.0
        double d2 = Math.sqrt(-4.0); // NaN 

7、public static double random(),伪随机数

返回带正号的 double 值,该值大于等于 0.0 且小于 1.0

将 [0.0, 1.0) 范围的值映射到 [0.0, 1.0] 范围,精确达到 1.0 是不可能的

        System.out.println(Math.random()); // 0.9820690172428007
        double ranNum1 = Math.ceil(Math.random()); // 向上取整,可能包括 1.0
        double ranNum2 = Math.random() * 2;
        if (ranNum2 >= 1.0) {
            ranNum2 = 1.0; // 如果大于等于 1.0,则将其设为 1.0
        }

三、练习题

1、依据绝对值,计算范围内的整数个数

范围 [-5.8, 6.9],绝对值 > 6.0 或者 < 2.1 的整数有几个?

 		int count = 0;
        int min = (int) -5.8; // -5 
        int max = (int) 6.9;  //  6
		// int min = (int) Math.ceil(-5.8);
        // int max = (int) Math.floor(6.9);
        for (int i = min; i <= max; i++) { // 1、确定整数范围 [-5, 6]
            int abs = Math.abs(i);
            if (abs > 6.0 || abs < 2.1) {  // 2、判断绝对值是否符合条件
                System.out.print(i + " ");
                count++;
            }
        }
        System.out.println("\n符合条件的整数有" + count + "个");

在这里插入图片描述
浮点数变成整数:四舍五入、向上向下取整、强制类型转换

		// 强制类型转换是直接将小数部分舍弃
		int i1 = (int) 100.26F; // 100
        int i2 = (int) 100.99D; // 100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼悠奕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值