第8 章 : 数字操作类
33 Math数学计算类
Math提供的方法都是static方法,都是基本数学公式
Math.abs(-10) // 10
Math.max(10, 1) // 10
Math.pow(10, 2) //100.0
Math.sqrt(9) //3.0
Math.round(10.4) // 10
Math.round(10.5) // 11
class MathUtil {
private MathUtil() {
}
// 自定义保留位数
public static double round(double num, int scale) {
return Math.round(num * Math.pow(10, scale)) / Math.pow(10, scale);
}
}
class Demo {
public static void main(String[] args) {
System.out.println(MathUtil.round(10.98766, 2)); // 10.99
}
}
34 Random随机数生成类
import java.util.Random;
class Demo {
public static void main(String[] args) {
Random random = new Random();
// 产生随机数范围[0, 10)
System.out.println(random.nextInt(10));
}
}
彩票号码生成示例
import java.util.Random;
/**
* 随机示例
* 36 选 7
*/
class Demo {
public static int[] getCodeList(){
int[] data = new int[7];
int foot = 0;
Random random = new Random();
while (foot
关注
打赏