前言
给定两个矩阵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
一、C语言解答
#include <stdio.h>
#define MAX 100
void SetNumber(int a[MAX][MAX], int r, int c);
int main()
{
int ra, ca, rb, cb;
int i, j, k;
int a[MAX][MAX], b[MAX][MAX], sum[MAX][MAX];
scanf("%d %d", &ra, &ca);
SetNumber(a, ra, ca);
scanf("%d %d", &rb, &cb);
SetNumber(b, rb, cb);
if (ca != rb)
{
printf("Error: %d != %d\n", ca, rb);
}
else
{
for (i = 0; i < ra; i++)
{
for (j = 0; j < cb; j++)
{
sum[i][j] = 0;
for (k = 0; k < ca; k++)
{
sum[i][j] += a[i][k]*b[k][j];
}
}
}
printf("%d %d\n", ra, cb);
for (i = 0; i < ra; i++)
{
for (j = 0; j < cb; j++)
{
printf("%d", sum[i][j]);
if (j != cb - 1)
{
printf(" ");
}
}
printf("\n");
}
}
return 0;
}
void SetNumber(int a[][MAX], int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", &a[i][j]);
}
}
return;
}
二、Python解答
A, B, Y= [], [], []
ax, ay = map(int, input().split())
for i in range(ax):
tempa = list(map(int, input().split()))
A.append(tempa)
bx, by = map(int, input().split())
for i in range(bx):
tempb = list(map(int, input().split()))
B.append(tempb)
if ay == bx:
print(ax, by)
for i in range(ax):
temp1 = []
for j in range(by):
tempSum = 0
for z in range(ay):
tempSum += A[i][z]* B[z][j]
temp1.append(tempSum)
Y.append(temp1)
for i in Y:
print(' '.join(map(str, i)))
else:
print("Error: {0:} != {1:}".format(ay, bx))
总结
提示:对于列表ls = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]若要实现输出格式为:
a b c d e
可使用
print(' '.join(ls))
实现。但是对于数字列表,如lsnum = [1, 2, 3, 4, 5],则需要用
print(' '.join(map(str, lsnum)))
来实现输入格式如下
1 2 3 4 5
的情况。