碰巧解决PTA L1-048 矩阵A乘以B (15分) -- 我终于用Java解出来了

L1-048 矩阵A乘以B (15分)

给定两个矩阵A和B,要求你计算它们的乘积矩阵AB。需要注意的是,只有规模匹配的矩阵才可以相乘。即若A有R
​a
​​ 行、C
​a
​​ 列,B有R
​b
​​ 行、C
​b
​​ 列,则只有C
​a
​​ 与R
​b
​​ 相等时,两个矩阵才能相乘。

输入格式:
输入先后给出两个矩阵A和B。对于每个矩阵,首先在一行中给出其行数R和列数C,随后R行,每行给出C个整数,以1个空格分隔,且行首尾没有多余的空格。输入保证两个矩阵的R和C都是正数,并且所有整数的绝对值不超过100。

输出格式:
若输入的两个矩阵的规模是匹配的,则按照输入的格式输出乘积矩阵AB,否则输出Error: Ca != Rb,其中Ca是A的列数,Rb是B的行数。

输入样例1:

2 3
1 2 3
4 5 6
3 4
7 8 9 0
-1 -2 -3 -4
5 6 7 8

输出样例1:

2 4
20 22 24 16
53 58 63 28

输入样例2:

3 2
38 26
43 -5
0 17
3 2
-11 57
99 68
81 72

输出样例2:

Error: 2 != 3

我的解法:(我都傻了,卡的还是输入输出的点)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] s = reader.readLine().split(" ");
        int l1 = Integer.parseInt(s[0]);
        int c1 = Integer.parseInt(s[1]);
        int [][] nums1 = new int[l1][c1];
        for (int i = 0; i < l1; i++) {
            s = reader.readLine().split(" ");
            for (int j = 0; j < c1; j++) {
                nums1[i][j] = Integer.parseInt(s[j]);
            }
        }

        s = reader.readLine().split(" ");
        int l2 = Integer.parseInt(s[0]);
        int c2 = Integer.parseInt(s[1]);
        int [][] nums2 = new int[l2][c2];
        for (int i = 0; i < l2; i++) {
            s = reader.readLine().split(" ");
            for (int j = 0; j < c2; j++) {
                nums2[i][j] = Integer.parseInt(s[j]);
            }
        }

        if(c1 != l2) {
            System.out.printf("Error: %d != %d", c1, l2);
            return;
        }

        StringBuffer buffer = new StringBuffer();
        buffer.append(l1 + " " + c2 + "\n");
        for (int i = 0; i < l1; i++) {
            for (int j = 0; j < c2; j++) {
                int sum = 0;
                for (int k = 0; k < c1; k++) {
                    sum += nums1[i][k] * nums2[k][j];
                }
                buffer.append(sum);
                if(j == c2 - 1) continue;
                buffer.append(" ");
            }
            if(i == l1 - 1) continue;
            buffer.append("\n");
        }
        System.out.println(buffer.toString());
        reader.close();
    }

}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值