fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. // Function to calculate the determinant of a 2x2 matrix
  6. float determinant2x2(float a, float b, float c, float d) {
  7. return a * d - b * c;
  8. }
  9.  
  10. int main() {
  11. int n;
  12. cout << "Enter the order of square matrix: ";
  13. cin >> n;
  14.  
  15. if (n != 2) {
  16. cout << "This implementation currently supports only 2x2 matrices.\n";
  17. return 1;
  18. }
  19.  
  20. float A[2][2], B[2], invA[2][2], detA;
  21.  
  22. cout << "Enter coefficients of matrix A:\n";
  23. for (int i = 0; i < 2; i++)
  24. for (int j = 0; j < 2; j++)
  25. cin >> A[i][j];
  26.  
  27. cout << "Enter constants of vector B: ";
  28. for (int i = 0; i < 2; i++)
  29. cin >> B[i];
  30.  
  31. // Calculate determinant of A
  32. detA = determinant2x2(A[0][0], A[0][1], A[1][0], A[1][1]);
  33.  
  34. cout << "Determinant of A: " << detA << endl;
  35.  
  36. if (detA == 0) {
  37. cout << "Matrix is singular; the system is not uniquely solvable." << endl;
  38. return 1;
  39. }
  40.  
  41. // Calculate inverse of A (adjoint/det)
  42. invA[0][0] = A[1][1] / detA;
  43. invA[0][1] = -A[0][1] / detA;
  44. invA[1][0] = -A[1][0] / detA;
  45. invA[1][1] = A[0][0] / detA;
  46.  
  47. cout << "Inverse of matrix A:\n";
  48. for (int i = 0; i < 2; i++) {
  49. for (int j = 0; j < 2; j++)
  50. cout << fixed << setprecision(4) << setw(8) << invA[i][j] << " ";
  51. cout << endl;
  52. }
  53.  
  54. // Solve using Cramer's Rule
  55. float x1, x2;
  56. float D1 = determinant2x2(B[0], A[0][1], B[1], A[1][1]);
  57. float D2 = determinant2x2(A[0][0], B[0], A[1][0], B[1]);
  58.  
  59. x1 = D1 / detA;
  60. x2 = D2 / detA;
  61.  
  62. cout << "The solution using Cramer's Rule:\n";
  63. cout << "x1 = " << x1 << endl;
  64. cout << "x2 = " << x2 << endl;
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5296KB
stdin
2  5
-3 1
stdout
Enter the order of square matrix: Enter coefficients of matrix A:
Enter constants of vector B: Determinant of A: 1.53442e-40
Inverse of matrix A:
  0.2000      inf 
 -0.0000      inf 
The solution using Cramer's Rule:
x1 = 0.1444
x2 = 0.2406