在我们进行基础JAVA编程时,我们会使用到很多类,数学运算是我们肯定避免不了的一种,所以Math类十分常用而且重要。
Math类
第一步:打开API搜索Math。
第二步:查看成员变量:
代码示例:
public class Mathh {
public static void main(String[] args) {
System.out.println(Math.E);
System.out.println(Math.PI);
}
}
输出结果:
2.718281828459045
3.141592653589793
Math中没有构造方法,直接来看方法;因为太多,直接在代码中演示常用的:
public class Mathh {
public static void main(String[] args) {
//abs方法,求绝对值方法,重载的有double型,float型,int型,long型
System.out.println(Math.abs(-3443.344));
//cbrt方法,开立方根
System.out.println(Math.cbrt(27));
//ceil向上取整,floor向下取整
System.out.println(Math.ceil(3.444));
System.out.println(Math.floor(3.444));
//round方法,四舍五入返回一个整数
System.out.println(Math.round(1.45));
System.out.println(Math.round(1.51));
//random方法,产生一个大于等于0,小于1的随机数
System.out.println(Math.round(Math.random()*10+1));
}
}
输出结果:
3443.344
3.0
4.0
3.0
1
2
8