3

## C語言短陣相乘的問題

wani 2020-11-06 11:16:491250 瀏覽

2 3
1 2 3
4 5 6
2 1
1
0
2 3
1 2 3
4 5 6
3 2
1 0
0 1
1 0

Invalid calculation!!
4 2
10 5

#include <stdio.h>

int main ()

{
int a[10][10],b[10][10],c[10][10];
int i, j, k;

for (i = 0; i < 2; i++)

for (j = 0; j < 2; j++) {

c[i][j] = 0;

for (k = 0; k < 3; k++)

c[i][j] += a[i][k] * b[k][j];

}

}

int main(void)

{

int i, j;

int A[2][3];

int B[2][1] ;

int z[2][2];

for (i = 0; i < 2; i++) {

for (j = 0; j < 2; j++)

printf("%3d", z[i][j]);

putchar('\n');

}

void mul(const int ma[2][3], const int mb[3][2], int mc[2][2])

{

int i, j, k;

for (i = 0; i < 2; i++)

for (j = 0; j < 2; j++) {

mc[i][j] = 0;

for (k = 0; k < 3; k++)

mc[i][j] += ma[i][k] * mb[k][j];

}

}

return (0);

}

### 1 個回答

8

iT邦大神 1 級 ‧ 2020-11-06 11:27:09

``````#include <stdio.h>

void getMatrixElements(int matrix[][10], int row, int column) {

for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
scanf("%d", &matrix[i][j]);
}
}
}

void multiplyMatrices(int first[][10],
int second[][10],
int result[][10],
int r1, int c1, int r2, int c2) {

for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
result[i][j] = 0;
}
}

for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
}

void display(int result[][10], int row, int column) {

for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("%d  ", result[i][j]);
if (j == column - 1)
printf("\n");
}
}
}

int main() {
int first[10][10], second[10][10], result[10][10], r1, c1, r2, c2;

while (scanf("%d %d", &r1, &c1) != EOF) {
getMatrixElements(first, r1, c1);

scanf("%d %d", &r2, &c2);
getMatrixElements(second, r2, c2);

if (c1 != r2) {
printf("Invalid calculation!!\n");
} else {
multiplyMatrices(first, second, result, r1, c1, r2, c2);
display(result, r1, c2);
}
}

return 0;
}
``````

froce iT邦大師 1 級 ‧ 2020-11-06 13:11:25 檢舉

JS:A class?Please run it in chrome

fillano iT邦超人 1 級 ‧ 2020-11-07 14:55:27 檢舉

JS: class is nothing but a syntactic sugar for constructor function.