JavaAPI-Math 类

一、Math 类

1.1、Math 类概述

  • Math 类在 java.lang 包下,所以使用的时候不需要导包。
  • Math 包含执行基本数字运算的方法,如基本指数,对数,平方根和三角函数。
  • Math 类没有构造方法,但是其方法都被 static 修饰了,所以可以直接 Math.方法名(参数)

1.2、Math 类的常用方法

方法名 说明
public static int abs(int a) 返回参数的绝对值
public static double ceil(double a) 返回大于或等于参数的最小 double 值,等于一个整数
public static double floor(double a) 返回小于或等于参数的最大 double 值,等于一个整数
public static int round(float a) 按照四舍五入返回最接近参数的int
public static int max(int a,int b) 返回两个 int 值中的较大值
public static int min(int a,int b) 返回两个 int 值中的较小值
public static double pow(double a,double b) 返回 a 的 b 次幂的值
public static double random() 返回值为 double 的正值,[0.0,1.0)

1.2.1、abs(int a) 方法

  • 返回参数的绝对值。
System.out.println(Math.abs(88));
System.out.println(Math.abs(-88));

1.2.2、ceil(double a) 方法

  • 返回大于或等于参数的最小 double 值,等于一个整数。
System.out.println(Math.ceil(12.34));
System.out.println(Math.ceil(12.56));

1.2.3、floor(double a) 方法

  • 返回小于或等于参数的最大 double 值,等于一个整数。
System.out.println(Math.floor(12.34));
System.out.println(Math.floor(12.56));

1.2.4、round(float a) 方法

  • 按照四舍五入返回最接近参数的int。
System.out.println(Math.round(12.34));
System.out.println(Math.round(12.56));
System.out.println("----------");
System.out.println(Math.round(12.34F));
System.out.println(Math.round(12.56F));

1.2.5、max(int a,int b) 方法

  • 返回两个 int 值中的较大值。
System.out.println(Math.max(66,88));

1.2.6、min(int a,int b) 方法

  • 返回两个 int 值中的较小值。
System.out.println(Math.min(66,88));

1.2.7、pow(double a,double b) 方法

  • 返回 a 的 b 次幂的值。
System.out.println(Math.pow(2.0,3.0));

1.2.8、random() 方法

  • 返回值为 double 的正值,[0.0,1.0)。
System.out.println(Math.random());

// 把随机数扩大 10 倍并强制转换为 int 类型,+1 把 9 变成 1。
System.out.println((int) (Math.random() * 10) + 1);
posted @ 2021-02-20 10:14    阅读(97)  评论(0)    收藏  举报