use*_*634 0 java arrays matrix
所以我有一个代码,将打印一个二维数组的表.我遇到的问题是我完全不知道如何繁殖并找到数组的乘积.任何帮助表示赞赏.谢谢
public class MultiplyingArrays {
public static void main(String[] args) {
int firstarray[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
int secondarray[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
System.out.println("This is the first array");
display(firstarray);
System.out.println("This is the second array");
display(secondarray);
}
public static void display(int x[][]) {
for (int row = 0; row < x.length; row++) {
for (int column = 0; column < x[row].length; column++) {
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
}
Run Code Online (Sandbox Code Playgroud)
期望的结果是:
-3 43
18 60
1 -20
Run Code Online (Sandbox Code Playgroud)
int firstarray[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
int secondarray[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
/* Create another 2d array to store the result using the original arrays' lengths on row and column respectively. */
int [][] result = new int[firstarray.length][secondarray[0].length];
/* Loop through each and get product, then sum up and store the value */
for (int i = 0; i < firstarray.length; i++) {
for (int j = 0; j < secondarray[0].length; j++) {
for (int k = 0; k < firstarray[0].length; k++) {
result[i][j] += firstarray[i][k] * secondarray[k][j];
}
}
}
/* Show the result */
display(result);
Run Code Online (Sandbox Code Playgroud)
PS使用适当的命名约定.
| 归档时间: |
|
| 查看次数: |
44707 次 |
| 最近记录: |