Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 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. 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. int i,j;
  20. for(i=0;i<3;i++){
  21. for(j=0;j<3;j++){
  22. bs[i][j] = A[i][j];
  23. }
  24. }
  25.  
  26. for(i=0;i<3;i++){
  27. bs[i][n] = b[i];
  28. }
  29. }
  30.  
  31. int main()
  32. {
  33. int i,j,k;
  34. int **A = (int**)malloc(sizeof(int*)*3);
  35. int *b = (int*)malloc(sizeof(int)*3);
  36. for(i=0;i<3;i++){
  37. A[i] = (int*)calloc(3,sizeof(int));
  38. }
  39.  
  40. for(i=0;i<3;i++){
  41. printf("Enter equation %d: ",i+1);
  42. for(j=0;j<4;j++){
  43. if(j<3){
  44. scanf("%d",&A[i][j]);
  45. }else{
  46. scanf("%d",&b[i]);
  47. }
  48. }
  49. }
  50.  
  51. int det = det3(A);
  52. if(det == 0){
  53. printf("System does not have a unique solution because determinant is 0\n");
  54. }
  55. else
  56. {
  57. int **bs = (int**)malloc(sizeof(int*)*3);
  58. for(i=0;i<3;i++){
  59. bs[i] = (int*)calloc(3,sizeof(int));
  60. }
  61.  
  62. int *detB = (int*)calloc(3,sizeof(int));
  63.  
  64. for(i=0;i<3;i++){
  65. copyAbtoB(A,b,bs,i);
  66. detB[i] = det3(bs);
  67. }
  68.  
  69. float x = (detB[0]*1.0)/(det*1.0);
  70. float y = (detB[1]*1.0)/(det*1.0);
  71. float z = (detB[2]*1.0)/(det*1.0);
  72.  
  73. printf("System has unique solution ( %f, %f, %f)\n",x,y,z);
  74.  
  75. }
  76.  
  77. return(0);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement