fork download
  1. /*
  2. Name: Md. Shahin Shiddik Shuvon
  3. Id: 230241011
  4. Report: Cramer's rule
  5. */
  6. #include <bits/stdc++.h>
  7. using namespace std;
  8.  
  9.  
  10. // 3x3 determinant
  11. float det3x3(float m[3][3]) {
  12. return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1])
  13. - m[0][1]*(m[1][0]*m[2][2] - m[1][2]*m[2][0])
  14. + m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);
  15. }
  16.  
  17. int main() {
  18. int n;
  19. cin >> n;
  20.  
  21.  
  22.  
  23. float A[3][3] = {0}, B[3] = {0}; // initialized to 0
  24.  
  25. cout << "Enter coefficients of matrix A:\n";
  26. for (int i = 0; i < n; i++)
  27. for (int j = 0; j < n; j++)
  28. cin >> A[i][j];
  29.  
  30. cout << "Enter constants of vector B:\n";
  31. for (int i = 0; i < n; i++)
  32. cin >> B[i];
  33.  
  34.  
  35. float detA = det3x3(A);
  36. cout << "\nDeterminant of A: " << detA << endl;
  37. if (detA == 0) {
  38. cout << "Matrix is singular; not uniquely solvable.\n";
  39. return 0;
  40. }
  41.  
  42. float A1[3][3], A2[3][3], A3[3][3];
  43. for (int i = 0; i < 3; i++) {
  44. A1[i][0] = B[i]; A1[i][1] = A[i][1]; A1[i][2] = A[i][2];
  45. A2[i][0] = A[i][0]; A2[i][1] = B[i]; A2[i][2] = A[i][2];
  46. A3[i][0] = A[i][0]; A3[i][1] = A[i][1]; A3[i][2] = B[i];
  47. }
  48.  
  49. float x1 = det3x3(A1) / detA;
  50. float x2 = det3x3(A2) / detA;
  51. float x3 = det3x3(A3) / detA;
  52.  
  53. cout << "\nThe solution using Cramer's Rule:\n";
  54. cout << "x1 = " << x1 << endl;
  55. cout << "x2 = " << x2 << endl;
  56. cout << "x3 = " << x3 << endl;
  57.  
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 5320KB
stdin
3
1 1 1
2 3 5
4 0 5

5 8 2
stdout
Enter coefficients of matrix A:
Enter constants of vector B:

Determinant of A: 13

The solution using Cramer's Rule:
x1 = 3
x2 = 4
x3 = -2