Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 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.  
  8. #include<stdio.h>
  9. #include<stdlib.h>
  10. #include<math.h>
  11.  
  12. // A is a 3*3 matrix
  13. int det3(int **A)
  14. {
  15. 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]);
  16. return (det);
  17. }
  18.  
  19. void copyAbtoB(int **A, int*b, int **bs, int n)
  20. {
  21. int i,j;
  22. for(i=0;i<3;i++)
  23. {
  24. for(j=0;j<3;j++)
  25. {
  26. bs[i][j] = A[i][j];
  27. }
  28. }
  29.  
  30. for(i=0;i<3;i++)
  31. {
  32. bs[i][n] = b[i];
  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. A[i] = (int*)calloc(3,sizeof(int));
  43. }
  44.  
  45. for(i=0;i<3;i++){
  46. printf("Enter equation %d: ",i+1);
  47. for(j=0;j<4;j++){
  48. if(j<3){
  49. scanf("%d",&A[i][j]);
  50. }else{
  51. scanf("%d",&b[i]);
  52. }
  53. }
  54. }
  55.  
  56. int det = det3(A);
  57. if(det == 0){
  58. printf("System does not have a unique solution because determinant is 0\n");
  59. }
  60. else
  61. {
  62. int **bs = (int**)malloc(sizeof(int*)*3);
  63. for(i=0;i<3;i++){
  64. bs[i] = (int*)calloc(3,sizeof(int));
  65. }
  66.  
  67. int *detB = (int*)calloc(3,sizeof(int));
  68.  
  69. for(i=0;i<3;i++){
  70. copyAbtoB(A,b,bs,i);
  71. detB[i] = det3(bs);
  72. }
  73.  
  74. float x = (detB[0]*1.0)/(det*1.0);
  75. float y = (detB[1]*1.0)/(det*1.0);
  76. float z = (detB[2]*1.0)/(det*1.0);
  77.  
  78. printf("System has unique solution ( %f, %f, %f)\n",x,y,z);
  79.  
  80. }
  81.  
  82. return(0);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement