gpt4 book ai didi

java执行数组计算

转载 作者:行者123 更新时间:2023-12-02 05:44:15 26 4
gpt4 key购买 nike

下面的代码将打印两个方阵,我需要它们在两个矩阵之间执行乘法,但我似乎无法让该部分工作。我在问题所在的代码块之前添加了注释。但目前它打印的只是零。我在网上浏览了很多网站,但似乎无法让我的网站工作。

 import java.util.*;
import java.math.*;

public class Main {

public static void main(String[] args) {

//create the grid
final int rowWidth = 9;
final int colHeight = 9;

Random rand = new Random();

int [][] board = new int [rowWidth][colHeight];

//fill the grid
for (int row = 0; row < board.length; row++) {

for (int col = 0; col < board[row].length; col++) {

board[row][col] = rand.nextInt(10);
}
}

//display output
for(int i = 0; i < board.length; i++) {

for(int j = 0; j < board[i].length; j++) {

System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}

System.out.println();


int [][] board2 = new int [rowWidth][colHeight];

//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {

for (int col2 = 0; col2 < board[row2].length; col2++) {

board[row2][col2] = rand.nextInt(10);
}
}

//display output
for(int m = 0; m < board2.length; m++) {

for(int n = 0; n < board[m].length; n++) {

System.out.print(board[m][n] + " ");

}
System.out.println();
}

//error is somewhere here

int[][] calculationMultiplication = new int[rowWidth][colHeight];
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] = calculationMultiplication[l][t] + board[l][z] * board2[z][t];
}
}
}

//display output

System.out.println("\nProduct of the 2 matrices is ");
for (int i = 0; i < calculationMultiplication.length; i++) {
for (int j = 0; j < calculationMultiplication[0].length; j++) {
System.out.print(calculationMultiplication[i][j] + " ");
}
System.out.println();
}

} //end of main
} //end of class Main

最佳答案

问题是您尚未填充 board2 数组,因此它的所有元素都将为 0。在 for 循环中,您还应该为 board2 分配随机值。您对 board 数组执行了两次。

//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board2[row2].length; col2++) { // notice 'board2[row].length'
board2[row2][col2] = rand.nextInt(10);
}
}

您应该在显示数组的 for 循环中执行类似的操作:

//display output
for (int m = 0; m < board2.length; m++) {
for (int n = 0; n < board2[m].length; n++) { // notice 'board2[row].length'
System.out.print(board2[m][n] + " ");
}
System.out.println();
}

关于java执行数组计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24237283/

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