Skip to content

Instantly share code, notes, and snippets.

@chomado
Created June 7, 2013 06:10
Show Gist options
  • Save chomado/5727340 to your computer and use it in GitHub Desktop.
Save chomado/5727340 to your computer and use it in GitHub Desktop.
行列の積の求め方を知ったので、ユーザーの入力した2行3列の行列と、3行2列の行列の積を求めるものを書いてみました
/* 2行3列の行列と、3行2列の行列の積を求める */
#include <stdio.h>
int main(void) {
int i, j, k;
int mx[2][3], my[3][2], mz[2][2];
/* ---- 入力 -----*/
puts("行列mx, myの各要素を入力してください。");
puts("行列mx: 2行3列");
for (i=0; i<2; i++) {
for(j=0; j<3; j++) {
printf("mx[%d][%d]: ", i, j); scanf("%d", &mx[i][j]);
}
}
puts("行列my: 3行2列");
for (i=0; i<3; i++) {
for(j=0; j<2; j++) {
printf("my[%d][%d]: ", i, j); scanf("%d", &my[i][j]);
}
}
putchar('\n');
/* ---- 確認 -----*/
puts("[確認] あなたの入力した行列は、");
puts("行列mx:");
for (i=0; i<2; i++) {
for(j=0; j<3; j++) {
printf("%3d", mx[i][j]);
}
putchar('\n');
}
puts("行列my:");
for (i=0; i<3; i++) {
for(j=0; j<2; j++) {
printf("%3d", my[i][j]);
}
putchar('\n');
}
puts("です。");
/* ---- 計算 ----*/
for(i=0; i<2; i++) { // を2回(2列ずつ)やる
for(j=0; j<2; j++) {
mz[i][j] = 0;
for(k=0; k<3; k++) // 掛けて×3 それを足して×3
mz[i][j] += mx[i][k] * my[k][j];
}
}
putchar('\n');
/* ---- 計算結果表示 ----*/
puts("求める積は:");
for (i=0; i<2; i++) {
for (j=0; j<2; j++)
printf("%3d", mz[i][j]);
putchar('\n');
}
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment