随机生成【a,b】区间内的整数公式
(int)(Math.random() * (b - a + 1) + a)
举例:
生成[10, 19]区间的整数
Math.random() => [0, 1)
19 - 10 + 1 = 10
Math.random()*10 => [0, 10)
(int) Math.random()*10 => [0, 9]
(int) (Math.random()*10 + 10) => [10, 19]
代码如下(示例):
生成[10, 99]之间的整数。
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * (99 - 10 + 1) + 10);
System.out.print(array[i] + "\t");
}
System.out.println();