gpt4 book ai didi

java - 如何在 Java 中显示 N x N 随机数矩阵?

转载 作者:行者123 更新时间:2023-12-04 06:40:23 25 4
gpt4 key购买 nike

我正在尝试创建一个随机双数矩阵。矩阵的大小必须为 n x n,并且所有数字都必须在 1 到 100 之间。我多年来一直试图对其进行排序,我知道它一定很简单(通常是这样)。

这是我的代码:

public static void main(String[] args) { 
PrintRandomGraph(RandomArray(4));
}

private static double[] RandomArray(int n) {
double[] randomArray = new double[n];
double[][] randomMatrix = new double [n][n];

Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {

Integer r = rand.nextInt()% 100;
randomArray[i] = Math.abs(r);
for (int j = 0; j < n; j++) {
Arrays.fill(randomMatrix, i, i+1, randomArray);
}
}

return randomArray;
}

private static void PrintRandomGraph(double[] inputArray) {
int n = inputArray.length;
double[] showArray = new double[n];
double[][] showMatrix = new double [n][n];

for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
double r = inputArray[i];
showArray[i] = r;
Arrays.fill(showMatrix, i, i+1, showArray);
}
}

System.out.println(Arrays.deepToString(showMatrix));
}

当我运行代码时,我得到一个重复 n 次的随机数组,例如:

[[63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0]]



我想我需要回到 for 循环的顶部并添加新数组...?请帮忙=(

任何帮助深表感谢。谢谢你。

最佳答案

你有没有尝试过这样的事情:

private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];

Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}

}

return randomMatrix;
}

打印图形:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(array[i][j]);
}
}
}

用方括号打印图形:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" [ ");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]);
}
//Put println instead of print here to have each row in a new line
System.out.print(" ]");
}
}

另外,这看起来很像家庭作业,如果是,请像这样标记它:)

关于java - 如何在 Java 中显示 N x N 随机数矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4328442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com