首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从两个文件中读取两个矩阵,并输出两个相乘的矩阵

从两个文件中读取两个矩阵,并输出两个相乘的矩阵
EN

Stack Overflow用户
提问于 2015-11-07 11:20:53
回答 1查看 1.7K关注 0票数 0

我必须编写一个程序来读取具有文本矩阵的两个输入文件,将这些矩阵相乘,然后输出最终的矩阵。输出文件的第一行中必须包含矩阵的大小(即: 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

代码语言:javascript
复制
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;
    }
}
}

我意识到“结果”矩阵并不是真正的正确答案。我是否正确读取文件并将其设置为矩阵?我该怎么做才能将它们相乘呢?

EN

回答 1

Stack Overflow用户

发布于 2015-11-07 11:38:25

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33578785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档