1
在完成包含兩個二維數組並將它們相乘的程序時,遇到了一些麻煩。現在我能夠構建這些具有設定長度的數組,然後使用數字生成器來創建每個數組。至於第三個數組,我能夠建立數組的長度,但是當把三個數組放入一個方法時,我仍然有超出界限的問題。乘以多維數組
for(int k = 0; k < totalMatrix.length; k++)
矩陣:
public class arrayTest1{
public static void main (String [] args){
int matrix1[][] = new int [5][2];
for (int i = 0; i < matrix1.length; i++)
for (int j = 0; j < matrix1[i].length; j++)
matrix1[i][j] = (int)(Math.random() * 1000);
System.out.println("The array 1 is: ");
for (int i = 0; i < matrix1.length; i++){
for (int j = 0; j < matrix1[i].length; j++){
System.out.print(matrix1[i][j]+" ");
}
System.out.println();
}
int matrix2[][] = new int [2][5];
for (int i = 0; i < matrix2.length; i++)
for (int j = 0; j < matrix2[i].length; j++)
matrix2[i][j] = (int)(Math.random() * 1000);
System.out.println("The array 2 is: ");
for (int i = 0; i < matrix2.length; i++){
for (int j = 0; j < matrix2[i].length; j++){
System.out.print(matrix2[i][j]+" ");
}
System.out.println();
}
int matrixSum[][] = new int [matrix1.length][matrix2[0].length];
matrixMulti(matrix1,matrix2,matrixSum);
System.out.println("The array mutliplied is: ");
for (int i = 0; i < matrixSum.length; i++){
for (int j = 0; j < matrixSum[i].length; j++){
System.out.print(matrixSum[i][j]+" ");
}
System.out.println();
}
}
public static void matrixMutli(int [][] m1, int [][] m2,int [][] totalMatrix){
for(int i = 0; i < m1.length; i++)
for(int j = 0; j < m2[0].length; j++)
for(int k = 0; k < totalMatrix.length; k++)
totalMatrix [i][j] += m1[i][k] * m2[k][j];
}
}
究竟是什麼方法?你能提供代碼嗎? – IHazABone
我的不好。我基於我正在開發的一個附加程序的代碼。我重命名了引入matrixMulti數組的方法。 – user3015726