fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // 行列の掛け算を行う関数 (C = A * B)
  5. void multiply_matrices(int rows, int cols, double **A, double **B, double **C) {
  6. for (int i = 0; i < rows; i++) {
  7. for (int j = 0; j < cols; j++) {
  8. C[i][j] = 0;
  9. for (int k = 0; k < cols; k++) {
  10. C[i][j] += A[i][k] * B[k][j];
  11. }
  12. }
  13. }
  14. }
  15.  
  16. int main() {
  17. int rows, cols;
  18.  
  19. // 1. 行数と列数の読み込み
  20. if (scanf("%d %d", &rows, &cols) != 2) return 1;
  21. printf("指定サイズ: %d行 %d列\n", rows, cols);
  22.  
  23. // 2. メモリ確保 (行列A, A^2, A^3 用の3つを用意)
  24. double **A = (double **)malloc(rows * sizeof(double *));
  25. double **A2 = (double **)malloc(rows * sizeof(double *));
  26. double **A3 = (double **)malloc(rows * sizeof(double *));
  27. for (int i = 0; i < rows; i++) {
  28. A[i] = (double *)malloc(cols * sizeof(double));
  29. A2[i] = (double *)malloc(cols * sizeof(double));
  30. A3[i] = (double *)malloc(cols * sizeof(double));
  31. }
  32.  
  33. // 3. 各要素に数値を読み込む
  34. for (int i = 0; i < rows; i++) {
  35. for (int j = 0; j < cols; j++) {
  36. if (scanf("%lf", &A[i][j]) != 1) return 1;
  37. }
  38. }
  39.  
  40. // 4. 【一つ目の課題】入力された2次元配列を表示
  41. printf("\n--- 入力された2次元配列 (行列A) ---\n");
  42. for (int i = 0; i < rows; i++) {
  43. for (int j = 0; j < cols; j++) {
  44. printf("%g\t", A[i][j]);
  45. }
  46. printf("\n");
  47. }
  48.  
  49. // 5. 【二つ目の課題】行列の3乗を計算
  50. // A^2 = A * A
  51. multiply_matrices(rows, cols, A, A, A2);
  52. // A^3 = A^2 * A
  53. multiply_matrices(rows, cols, A2, A, A3);
  54.  
  55. // 6. 計算結果 (A^3) の表示
  56. printf("\n--- 行列の3乗 (A^3) の計算結果 ---\n");
  57. for (int i = 0; i < rows; i++) {
  58. for (int j = 0; j < cols; j++) {
  59. printf("%g\t", A3[i][j]);
  60. }
  61. printf("\n");
  62. }
  63.  
  64. // 7. メモリ解放
  65. for (int i = 0; i < rows; i++) {
  66. free(A[i]); free(A2[i]); free(A3[i]);
  67. }
  68. free(A); free(A2); free(A3);
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0.01s 5320KB
stdin
5 5
10 -2 0 0 0
-2 9 -1 0 0
0 -1 8 -2 0
0 0 -2 7 -1
0 0 0 -1 5
stdout
指定サイズ: 5行 5列

--- 入力された2次元配列 (行列A) ---
10	-2	0	0	0	
-2	9	-1	0	0	
0	-1	8	-2	0	
0	0	-2	7	-1	
0	0	0	-1	5	

--- 行列の3乗 (A^3) の計算結果 ---
1116	-552	54	-4	0	
-552	867	-226	48	-2	
54	-226	629	-350	40	
-4	48	-350	450	-114	
0	-2	40	-114	142