Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. // Name: Andrew Lebon
  2. // Date: 06 December, 2019
  3. // Prog: prog09.c
  4. // Desc: This program uses Cramer's Rule to find the solution of three linear equations in three variables.
  5. // The program does this by calling a function named det3, which recieves the starting address for
  6. // the 3x3 array and returns the determinant of that array.
  7. #include<stdio.h>
  8. #include<stdlib.h>
  9. #include<math.h>
  10.  
  11. // A is a 3*3 matrix
  12. int det3(int **A)
  13. {
  14. int det = A[0][0]*( A[1][1]*A[2][2] - A[1][2]*A[2][1] ) - A[0][1]*( A[1][0]*A[2][2] - A[1][2]*A[2][0] ) + A[0][2]*( A[1][0]*A[2][1] - A[1][1]*A[2][0] );
  15. return (det);
  16. }
  17.  
  18. void copyAbtoB(int **A, int*b, int **bs, int n)
  19. {
  20. int i,j;
  21. for(i=0;i<3;i++)
  22. {
  23. for(j=0;j<3;j++)
  24. {
  25. bs[i][j] = A[i][j];
  26. }
  27. }
  28.  
  29. for(i=0;i<3;i++)
  30. {
  31. bs[i][n] = b[i];
  32. }
  33. }
  34.  
  35.  
  36. int main()
  37. {
  38. int i,j,k;
  39. int **A = (int**)malloc(sizeof(int*)*3);
  40. int *b = (int*)malloc(sizeof(int)*3);
  41. for(i=0;i<3;i++)
  42. {
  43. A[i] = (int*)calloc(3,sizeof(int));
  44. }
  45.  
  46. for(i=0;i<3;i++)
  47. {
  48. printf("Enter equation %d: ",i+1);
  49. for(j=0;j<4;j++)
  50. {
  51. if(j<3)
  52. {
  53. scanf("%d",&A[i][j]);
  54. }
  55. else
  56. {
  57. scanf("%d",&b[i]);
  58. }
  59. }
  60. }
  61.  
  62. int det = det3(A);
  63. if(det == 0)
  64. {
  65. printf("System does not have a unique solution because determinant is 0\n");
  66. }
  67. else
  68. {
  69. int **bs = (int**)malloc(sizeof(int*)*3);
  70. for(i=0;i<3;i++)
  71. {
  72. bs[i] = (int*)calloc(3,sizeof(int));
  73. }
  74.  
  75. int *detB = (int*)calloc(3,sizeof(int));
  76.  
  77. for(i=0;i<3;i++)
  78. {
  79. copyAbtoB(A,b,bs,i);
  80. detB[i] = det3(bs);
  81. }
  82.  
  83. float x = (detB[0]*1.0)/(det*1.0);
  84. float y = (detB[1]*1.0)/(det*1.0);
  85. float z = (detB[2]*1.0)/(det*1.0);
  86.  
  87. printf("System has unique solution ( %f, %f, %f)\n",x,y,z);
  88.  
  89. }
  90.  
  91. return(0);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement