1230: 矩阵乘法

xiaoxiao2021-02-28  170

题目

Description

矩阵乘法是线性代数中最基本的运算之一。 给定三个矩阵 A\B\C 请编写程序判断A*B = C 是否成立。 Input

输入包含多组数据。每组数据的格式如下: 第一行包括两个整数p 和q,表示矩阵A 的大小。后继p 行,每行有q 个整数,表示矩阵A 的元素内容。 紧接着用相同的格式给出矩阵B 和矩阵C。 输入数据的最后一行是两个0,你的程序处理到这里时就应该退出了。 输入数据中所有的整数绝对值都不超过100。 Output

对每一组输入数据,你的程序都要输出单独一行字符。 如果 A*B=C成立则输出”Yes” 如果 A 和B 根本不能相乘,或A*B=C不成立,则输出”No”。注意大小写。 Sample Input

2 3 1 2 3 4 5 6 3 2 1 2 3 4 5 6 2 2 22 28 49 64 1 2 1 2 2 1 2 1 2 2 2 4 1 2 1 2 1 2 1 1 1 1 1 1

0 0 Sample Output

Yes No No


代码块

import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cn = new Scanner(System.in); while (cn.hasNext()) { int pA = cn.nextInt(); int qA = cn.nextInt(); if(pA==0&&qA==0) return; int[][] a = new int[pA][qA]; for (int i = 0; i < pA; i++) for (int j = 0; j < qA; j++) a[i][j] = cn.nextInt(); int pB = cn.nextInt(); int qB = cn.nextInt(); int[][] b = new int[pB][qB]; for (int i = 0; i < pB; i++) for (int j = 0; j < qB; j++) b[i][j] = cn.nextInt(); int pC = cn.nextInt(); int qC = cn.nextInt(); int[][] c = new int[pC][qC]; for (int i = 0; i < pC; i++) for (int j = 0; j < qC; j++) c[i][j] = cn.nextInt(); if (qA == pB) { if (qC == qB && pC == pA) { int[][] as = new int[pC][qC]; for (int i = 0; i < pC; i++) { for (int j = 0; j < qC; j++) { as[i][j] = 0; } } int z[][] = new int[a.length][b[0].length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < b[0].length; j++) { int temp = 0; for (int x = 0; x < b.length; x++) { temp += a[i][x] * b[x][j]; } z[i][j] = temp; } } boolean flag = true; for (int i = 0; i < pC; i++) { for (int j = 0; j < qC; j++) { if(z[i][j]!=c[i][j]) { System.out.println("No"); flag = false; break; } } if(!flag) break; } if(flag) System.out.println("Yes"); } else System.out.println("No"); } else System.out.println("No"); } cn.close(); } }
转载请注明原文地址: https://www.6miu.com/read-20541.html

最新回复(0)