【发布时间】:2019-02-11 13:45:23
【问题描述】:
我有一个函数,可以在其中输入多维数组 n 的大小。接下来,我用 [-n, n] 范围内的随机数填充这个数组,使用 Math.random():
private int[][] enterMatrixSize() {
System.out.print("enter matrix size (n): ");
String input;
while (!(input = in.next()).matches("\\p{Digit}+")) {
System.out.print("Please enter a positive Integer: ");
}
int size = Integer.parseInt(input);
int[][] array = new int[size][size];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = (int) (Math.round(Math.random() * (size + 1)) - size / 2);
}
}
for (int i = 0; i < array.length; i++, System.out.println()) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]+" ");
}
}
return array;
}
但它显示了一些不正确的值。例如,当我输入 n 等于 1 时 - 显示数字 0、1 和 2。这很奇怪。因为应该输出 -1, 0, 1
【问题讨论】:
-
将
size + 1替换为size否则将随机数上移@987654324@,这就是您获得当前输出的原因 -
因为 1.5 轮是 2,所以换句话说,假设 random()=1 和 size=1 那么你有 1*(1+1))-1/2 所以 (2-1) /2,改为使用 .floor(x) 方法
-
@vmrvector 然后
Math.floor()可以完全省略,转换为int将已经丢弃所有小数位,这与地板操作相同 -
@Lino 不适用于负数。
Math.floor(-1.5) == -2,而(int)(-1.5) == -1。 -
@DodgyCodeException 您完全正确,我的评论甚至指出:... 将丢弃所有小数位...,因此必须使用负数
Math.floor()用过的。虽然如果你已经可以使用 jdk 来解决这个问题,为什么还要提出这样的逻辑ThreadLocalRandom#nextInt(int, int):)