团体程序设计天梯赛-练习集 L1-048 矩阵A乘以B(15 分)java c语言

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

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

输入格式:

输入先后给出两个矩阵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

 用Java写(有一个超时了)

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n1=sc.nextInt();
		int n2=sc.nextInt();
		int[][] a = new int[100][100];
		int[][] b = new int[100][100];
		for (int i = 0; i < n1; i++) {
			for (int j = 0; j < n2; j++) {
				a[i][j]=sc.nextInt();
			}
		}
		int n3=sc.nextInt();
		int n4=sc.nextInt();
		for (int i = 0; i < n3; i++) {
			for (int j = 0; j < n4; j++) {
				b[i][j]=sc.nextInt();
			}
		}
		if(n2!=n3)
			System.out.println("Error: "+n2+" != "+n3);
		else {
			System.out.println(n1+" "+n4);
			for (int i = 0; i < n1; i++) {
				for (int j = 0; j < n4; j++) {
					int count =0;
					for (int k = 0; k < n2; k++) {
						count+=a[i][k]*b[k][j];
					}
					System.out.print(count);
					if(j<n4-1)
					System.out.print(" ");
				}
				System.out.print("\n");
			}
		}
	}
}

 用C写,一样的方法,完美通过

#include<stdio.h>
int main() {
	int n1,n2,n3,n4;
	int a[100][100]= {0},b[100][100]= {0};
	scanf("%d %d", &n1, &n2);
	for (int i = 0; i < n1; i++) {
		for (int j = 0; j < n2; j++) {
			scanf("%d",&a[i][j]);
		}
	}
	scanf("%d %d",&n3,&n4);

	for (int i = 0; i < n3; i++) {
		for (int j = 0; j < n4; j++) {
			scanf("%d",&b[i][j]);
		}
	}
	if(n2!=n3)
		printf("Error: %d != %d",n2,n3);
	else {
		printf("%d %d\n",n1,n4);

		for (int i = 0; i < n1; i++) {
			for (int j = 0; j < n4; j++) {
				int count =0;
				for (int k = 0; k < n2; k++) {
					count+=a[i][k]*b[k][j];
				}
				printf("%d",count);
				if(j<n4-1)
					printf(" ");
			}
			printf("\n");
		}
	}
}

综上所述:C语言还是很强大的

猜你喜欢

转载自blog.csdn.net/qq_40674583/article/details/81568985