Java - Math

Math

Math位于java.lang包下,它 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。Math 的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用。下面看一下它所包含的两个常量和常用的一些方法。

常量

  • E:双精度的自然对数的底数
  • PI:近似的圆周率
public class MathTest {
    public static void main(String[] args) {
        System.out.println(Math.E);  // 2.718281828459045
        System.out.println(Math.PI); // 3.141592653589793
        
    }
}

常用方法:

  • abs(x):返回绝对值
  • ceil(x):取上边界整数值
  • floor(x):取下边界整数值
  • rint(x):返回与x最接近的double型整数
  • round(x):返回四舍五入的整数
  • min(x, y):返回x和y之间的最小值
  • max(x, y):返回x和y之间的最大值
  • exp(x):返回自然数底数e的参数次方
  • log(x):返回x的自然数底数的对数值
  • pow(x, y): 返回第一个参数的第二个参数次方
  • srqt(x): 返回x的平方根
  • sin(x)、cos(x)、tan(x): 返回x的正弦值、余弦值和正切值
  • asin(x)、acos(x)、atan(x): 返回x的反正弦值、反余弦值和反正切值
  • random(): 返回一个0到1之间的随机数
package MathTest;

public class MathTest {
    public static void main(String[] args) {
        System.out.println(Math.abs(4)); // 4
        System.out.println(Math.abs(-4)); // 4

        System.out.println(Math.floor(1.6)); // 1.0
        System.out.println(Math.ceil(1.6));  // 2.0

        System.out.println(Math.min(2, 6)); // 2
        System.out.println(Math.max(2, 6)); // 6

        System.out.println(Math.exp(2)); // 7.38905609893065
        System.out.println(Math.log(2)); // 0.6931471805599453

        System.out.println(Math.pow(2, 3)); // 8.0
        System.out.println(Math.sqrt(4));  // 2.0

        System.out.println(Math.sin(4.0));  // -0.7568024953079282
        System.out.println(Math.asin(-0.7568024953079282));  // -0.8584073464102067

        System.out.println(Math.random());  // 0.7898083114483953

    }
}

发布了461 篇原创文章 · 获赞 122 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/Forlogen/article/details/105609769