fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5.  
  6. void det_calc(double *matrix, int pivot[], int dim){
  7. int m, n, p;
  8. double *mat, *row, *col, max;
  9. mat = matrix;
  10. for (p = 0; p < dim; mat += dim, p++){ // Get the pivot
  11. pivot[p] = p;
  12. max = fabs(*(mat + p));
  13. row = mat + dim;
  14. for (n = p + 1; n < dim; n++, row += dim){
  15. if (max < fabs(*(row + p))){
  16. max = fabs(*(row + p));
  17. pivot[p] = n;
  18. col = row;
  19. }
  20. }
  21. if (pivot[p] != p) // If pivot is diff from current row, swap
  22. for (n = 0; n < dim; n++){
  23. max = *(mat + n);
  24. *(mat + n) = *(col + n);
  25. *(col + n) = max;
  26. }
  27. if (*(mat + p) == 0) return; // Singular matrix
  28. row = mat + dim;
  29. for (m = p + 1; m < dim; row += dim, m++) // Get lower triangular matrix
  30. *(row + p) /= *(mat + p);
  31. row = mat + dim;
  32. for (m = p + 1; m < dim; row += dim, m++) // Update matrix
  33. for (n = p + 1; n < dim; n++)
  34. *(row + n) -= *(row + p) * *(mat + n);
  35. }
  36. }
  37.  
  38. int main(void){
  39. int dim;
  40. double result = 1.0;
  41. char line[100];
  42. char *p = line;
  43. fgets(line, sizeof(line), stdin); // Get the first number
  44. sscanf(line, "%d", &dim); // Convert to int
  45. double matrix[dim][dim];
  46. int pivot[dim]; // Array to track pivot
  47. for (int i = 0; i < dim; i++){
  48. fgets(line, sizeof(line), stdin); // Get next line
  49. while (*p){ // Read until end of line
  50. for (int j = 0; j < dim; j++)
  51. matrix[i][j] = strtod(p, &p); // Convert to double
  52. p++;
  53. }
  54. p = line;
  55. }
  56. for (int i = 0; i < dim; i++){
  57. for (int j = 0; j < dim; j++){
  58. printf("%.1f ", matrix[i][j]);
  59. } printf("\n");
  60. }
  61. det_calc(&matrix[0][0], pivot, dim);
  62. for(int i = 0; i < dim; i++) result *= matrix[i][i];
  63. printf("%f", result);
  64. return 0;
  65. }
Success #stdin #stdout 0s 5516KB
stdin
9
0 0 0 0 0 0 2 3 1
0 0 0 7 3 2 3 3 1
0 0 0 0 9 10 2 8 3
0 0 0 0 0 0 0 6 4
0 4 7 10 5 10 5 9 6
0 0 0 0 0 3 9 9 6
2 1 2 1 7 6 3 10 9
0 0 5 7 7 3 10 2 5
0 0 0 0 0 0 0 0 5
stdout
0.0 0.0 0.0 0.0 0.0 0.0 2.0 3.0 1.0 
0.0 0.0 0.0 7.0 3.0 2.0 3.0 3.0 1.0 
0.0 0.0 0.0 0.0 9.0 10.0 2.0 8.0 3.0 
0.0 0.0 0.0 0.0 0.0 0.0 0.0 6.0 4.0 
0.0 4.0 7.0 10.0 5.0 10.0 5.0 9.0 6.0 
0.0 0.0 0.0 0.0 0.0 3.0 9.0 9.0 6.0 
2.0 1.0 2.0 1.0 7.0 6.0 3.0 10.0 9.0 
0.0 0.0 5.0 7.0 7.0 3.0 10.0 2.0 5.0 
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
0.000000