fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define N 4
  5.  
  6. void print_matrix(double A[][N+1]);
  7. void swap_rows(double A[][N+1], int row1, int row2);
  8. void diagonal_dominance(double A[][N+1]);
  9.  
  10. // 行列を表示する関数
  11. void print_matrix(double A[][N+1]) {
  12. for (int i = 0; i < N; i++) {
  13. for (int j = 0; j < N+1; j++) {
  14. printf("%lf ", A[i][j]);
  15. }
  16. printf("\n");
  17. }
  18. }
  19.  
  20. // 行列の2行を交換する関数
  21. void swap_rows(double A[][N+1], int row1, int row2) {
  22. for (int i = 0; i < N+1; i++) {
  23. double temp = A[row1][i];
  24. A[row1][i] = A[row2][i];
  25. A[row2][i] = temp;
  26. }
  27. }
  28.  
  29. // 対角優位化を行う関数
  30. void diagonal_dominance(double A[][N+1]) {
  31. for (int i = 0; i < N; i++) {
  32. double sum = 0;
  33. for (int j = 0; j < N; j++) {
  34. if (i != j) {
  35. sum += fabs(A[i][j]);
  36. }
  37. }
  38.  
  39. // 対角成分が非対角成分の和より小さい場合、行交換を試みる
  40. if (fabs(A[i][i]) < sum) {
  41. int max_row = i;
  42. double max_sum = 0;
  43.  
  44. // 交換可能な最大の対角優位行を探す
  45. for (int k = i+1; k < N; k++) {
  46. double row_sum = 0;
  47. for (int j = 0; j < N; j++) {
  48. if (k != j) {
  49. row_sum += fabs(A[k][j]);
  50. }
  51. }
  52.  
  53. if (fabs(A[k][k]) > row_sum && fabs(A[k][k]) > max_sum) {
  54. max_row = k;
  55. max_sum = row_sum;
  56. }
  57. }
  58.  
  59. // 行の交換
  60. if (max_row != i) {
  61. swap_rows(A, i, max_row);
  62. }
  63. }
  64. }
  65. }
  66.  
  67. int main() {
  68. double A[N][N+1] = {
  69. {0, 8, 1, 7, 14.41},
  70. {-2, 1, -3, 7, 15.11},
  71. {1, 6, 0, -1, 10.8},
  72. {5, -1, -2, 0, -1.32}
  73. };
  74.  
  75. printf("Original matrix:\n");
  76. print_matrix(A);
  77.  
  78. diagonal_dominance(A);
  79.  
  80. printf("\nMatrix after diagonal dominance:\n");
  81. print_matrix(A);
  82.  
  83. return 0;
  84. }
  85.  
  86.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Original matrix:
0.000000 8.000000 1.000000 7.000000 14.410000 
-2.000000 1.000000 -3.000000 7.000000 15.110000 
1.000000 6.000000 0.000000 -1.000000 10.800000 
5.000000 -1.000000 -2.000000 0.000000 -1.320000 

Matrix after diagonal dominance:
0.000000 8.000000 1.000000 7.000000 14.410000 
-2.000000 1.000000 -3.000000 7.000000 15.110000 
1.000000 6.000000 0.000000 -1.000000 10.800000 
5.000000 -1.000000 -2.000000 0.000000 -1.320000