欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

备战蓝桥杯java(六):算法竞赛中的常用API :Math类

程序员文章站 2022-03-04 20:11:34
...

Math类包含了一些常用的数学方法,在java.lang.*包内
(不能用于大数类,大数类请参见备战蓝桥杯java(五):算法竞赛中的常用API :大数类)

求最值

最小值

Math.min(int a, int b)
Math.min(float a, float b)
Math.min(double a, doubleb)
Math.min(long a, long b)

最大值

Math.max(int a, int b)
Math.max(float a, float b)
Math.max(double a, doubleb)
Math.max(long a, long b)

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

public class Main{
	public static void main(String[] args){
		int a = 10;
		int b = 20;
		System.out.println(Math.min(a, b));
		System.out.println(Math.max(a, b));
	}
}

求平方根

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


求绝对值

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

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

求幂(a^b)

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

实例:
备战蓝桥杯java(六):算法竞赛中的常用API :Math类
所以要求int类型的幂时,要对结果进行类型转换。

取整

  1. Math.ceil(double x)
    向上取整,返回大于该值的最近 double 值

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

    System.out.println(Math.floor(1.6)); // 1.0
    System.out.println(Math.floor(-1.6)); // -2.0
    
  3. 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.random()
生成一个[0,1)之间的double类型的伪随机数

所以为了得到一个[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.cos(double a) 余弦
  • Math.acos(double a) 反余弦
  • Math.sin(double a) 正弦值
  • Math.asin(double a) 反正弦值
  • Math.tan(double a) 正切值
  • Math.atan(double a) 反正切

我们可以用acos()方法求π
因为
cos(π) = -1
所以
acos(-1) = π