我必须编写一个程序来读取具有文本矩阵的两个输入文件,将这些矩阵相乘,然后输出最终矩阵。矩阵的大小(即:4x3,2x3)必须包含在输出文件的第一行中。
File1中:
4×2:
1 2
3 4
5 6
7 8
文件2:
2×3
1 2 3
4 5 6
输出:
4×3
9 12 15
19 26 33
29 40 51
39 54 69
package Programs;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Matrix {
public static void multiply(File input_file1, File input_file2, File output_file) {
try {
Scanner firstScan = new Scanner(input_file1);
Scanner secondScan = new Scanner(input_file2);
PrintWriter writer = new PrintWriter(output_file);
int[][] matrixOne = new int[][] {};
int[][] matrixTwo = new int[][] {};
firstScan.nextLine();
secondScan.nextLine();
while (firstScan.hasNext()) {
for (int row = 0; row < input_file1.length(); row++) {
for (int col = 0; col < input_file1.length(); col++) {
matrixOne[row][col] = firstScan.nextInt();
}
}
}
while (secondScan.hasNext()) {
for (int row = 0; row < input_file2.length(); row++) {
for (int col = 0; col < input_file2.length(); col++) {
matrixTwo[row][col] = secondScan.nextInt();
}
}
}
int [][] result = new int[][] {};
writer.println(result);
} catch (FileNotFoundException e) {
return;
}
}
}
我意识到&#34;结果&#34;矩阵不是实际的正确答案。我正在阅读并正确设置文件到矩阵吗?我该如何将它们相乘呢?
答案 0 :(得分:0)
public int[][] calMatrix(int[][] a, int[][] b) {
int c[][] = new int[a.length][b[0].length];
int x, i, j;
for (i = 0; i < a.length; i++) {
for (j = 0; j < b[0].length; j++) {
int temp = 0;
for (x = 0; x < b.length; x++) {
temp += a[i][x] * b[x][j];
}
c[i][j] = temp;
}
}
return c;
}
这是多重算法。
只需称呼它
有一个完全的答案。 this answer is right