javaMath类的使用相对比较简单,只要掌握了解一些相关的数学知识,配合API的使用,可以轻松的完成一些数学运算。
Math类提供了两个比较常用的常量:E 和 PI。
Math:
import java.util.Random;
public class MathTest {
public static void main(String[] args) {
useEandPI();
// useMath();
// useRandom();
}
private static void useEandPI() {
System.out.println(Math.E);
System.out.println(Math.PI);
/*
* 结果: 2.718281828459045 3.141592653589793
*/
}
// Math的简单操作
public static void useMath() {
double d1 = Math.ceil(12.23); // 取得大于12.23的最小整数。
double d2 = Math.floor(12.23); // 取得小于12.23的最大整数。
double d3 = Math.round(12.23); // 四舍五入
double d4 = Math.round(12.50003); // 四舍五入
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);
}
// 通过Random和Math方法获取随机数。
public static void useRandom() {
//Math方法获取随机数
for (int i = 0; i < 5; i++) {
System.out.println((int) (Math.random() * 10 + 1));
}
//Random方法获取随机数
Random random = new Random();
for (int i = 0; i < 5; i++) {
System.out.println(random.nextInt(10));
}
}
}