美文网首页
Java 数学运算 - Math类

Java 数学运算 - Math类

作者: Tinyspot | 来源:发表于2023-11-11 15:18 被阅读0次

1. java.lang.Math

public final class Math {
}

2. 数学常量

@Test
public void constant() {
    System.out.println("圆周率π=" + Math.PI);
    System.out.println("自然对数底数e=" + Math.E);
}

3. 指数函数

@Test
public void exponential() {
    System.out.println("算数平方根:" + Math.sqrt(4));
    System.out.println("N次方:" + Math.pow(2, 10));
    System.out.println("对数:" + Math.log10(201));
}

4. 取整函数

@Test
public void getInteger() {
    /**
     * Math.ceil(x) 向上取整,返回类型double
     */
    System.out.println(Math.ceil(1.2) + ", " + Math.ceil(1.8) + ", " + Math.ceil(-1.2) + ", " + Math.ceil(-1.8));

    /**
     * Math.floor(x) 向下取整,返回类型double
     */
    System.out.println(Math.floor(1.2) + ", " + Math.floor(1.8) + ", " + Math.floor(-1.2) + ", " + Math.floor(-1.8));

    /**
     * Math.round(x) 四舍五入取整,返回类型long
     */
    System.out.println(Math.round(1.2) + ", " + Math.round(1.8) + ", " + Math.round(-1.2) + ", " + Math.round(-1.8));

    // 取整,直接强转
    int floor = (int) Math.floor(1.2);
    System.out.println(floor);
}

打印结果:

2.0, 2.0, -1.0, -1.0
1.0, 1.0, -2.0, -2.0
1, 2, -1, -2
1

5. 最大最小值、绝对值

@Test
public void operate() {
    System.out.println("最大值:" + Math.max(2, 3));
    System.out.println("最小值:" + Math.min(2, 3));
    System.out.println("绝对值:" + Math.abs(-1));
}

6. 随机数

Math.random() 生成的是区间在[0,1)的随机小数 (double类型)

@Test
public void random() {
    Stream.generate(() -> Math.random())
            .limit(5)
            .forEach(System.out::println);
}

生成[1,10]的整数

@Test
public void random() {
    Stream.generate(() -> (int) (Math.random() * 10) + 1)
            .limit(5)
            .forEach(System.out::println);
}

相关文章

  • Java中 使用 Math 类操作数据

    使用 Math 类操作数据 Math 类位于 java.lang 包中,包含用于执行基本数学运算的方法, Math...

  • Java自学-数字与字符串 数学方法

    Java Math类常用方法 java.lang.Math提供了一些常用的数学运算方法,并且都是以静态方法的形式存...

  • JAVA(12)数字

    Math 类封装了常用的数学运算,提供了基本的数学操作,如指数、对数、平方根和三角函数等Math 类位于 java...

  • Java基础类库

    包 1、java.lang包:java类库中的核心部分,包含System系统类、数学运算的Math类、处理字符串的...

  • Java大数字运算BigDecimal 类!!!

    在Java中提供了用于大数字运算的类,即 java.math.BigInteger 类和 java.math.Bi...

  • Java大数字运算BigInteger类!!!

    在Java中提供了用于大数字运算的类,即 java.math.BigInteger 类和 java.math.Bi...

  • Java API(下)

    Math类和Random类 Math类 Math类是数学操作类,提供了一系列用于数学运算的静态方法,包括求绝对值、...

  • Java Math类,Random类,System类

    Math方法 Math:用于数学运算的类。 成员变量: public static final double PI...

  • Java Math类,Random类,System类

    Math的方法 /* Math:用于数学运算的类。 成员变量: public static final doubl...

  • 5 Math类

    在编写程序时,尤其时数学运算时,会涉及到很多的数学运算,Java提供了Math类,其中有很多方法可以实现各种数学运...

网友评论

      本文标题:Java 数学运算 - Math类

      本文链接:https://www.haomeiwen.com/subject/fzokwdtx.html