Math类中的常用方法
目录
一、Math类
二、Math类中的常用方法
1.Math.abs()
2.Math.max ()
3.Math.min
4.Math.pow ()
5.Math.random()
6.Math.ceil()
7.Math.floor()
8.Math.cbrt()
一、Math类
Java的Math类封装了很多与数学有关的属性和方法。
二、Math类中的常用方法
1.Math.abs()
求参数的绝对值
public class mathTest {
public static void main(String[] args) {
int a = Math.abs(-1);
int b =Math.abs(-2);
System.out.println(a);
System.out.println(b);
}
}
2.Math.max ()
返回两个 变量 值中较大的一个
public class mathTest {
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(Math.max(a, b));
}
}
3.Math.min
返回两个变量值中较小的一个
public class mathTest {
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(Math.min(a, b));
}
}
4.Math.pow ()
返回第一个参数的第二个参数次幂的值
public class mathTest {
public static void main(String[] args) {
int a = 2;
int b = 2;
System.out.println(Math.pow(a, b));
}
}
5.Math.random()
随机产生一个 [ 0 ,1)(左闭右开)之间的随机数 double类型。
public class mathTest {
public static void main(String[] args) {
for (int i = 0;i < 5;i++){
double a = Math.random();
System.out.println(a);
}
}
}
6.Math.ceil()
向上取整 和强制转化(int)a 整数部分相同
public class mathTest {
public static void main(String[] args) {
double a = 3.1415926;
System.out.println(Math.ceil(a));
}
}
7.Math.floor()
向下取整 和 强制转化 (int)a +1 整数部分相同
public class mathTest {
public static void main(String[] args) {
double a = 3.1415926;
System.out.println(Math.floor(a));
}
}
8.Math.cbrt()
求立方根
public class mathTest {
public static void main(String[] args) {
double a = 8;
System.out.println(Math.cbrt(a));
}
}
还没有评论,来说两句吧...