我必须编写一个程序来读取具有文本矩阵的两个输入文件,将这些矩阵相乘,然后输出最终的矩阵。输出文件的第一行中必须包含矩阵的大小(即: 4x3,2x3)。
File1:
4x2:
1 2
3 4
5 6
7 8
File2:
2x3
1 2 3
4 5 6
输出:
4x3
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;
}
}
}我意识到“结果”矩阵并不是真正的正确答案。我是否正确读取文件并将其设置为矩阵?我该怎么做才能将它们相乘呢?
发布于 2015-11-07 11:38:25
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
https://stackoverflow.com/questions/33578785
复制相似问题