Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Name: Andrew Lebon
- // Date: 06 December, 2019
- // Prog: prog09.c
- // Desc: This program uses Cramer's Rule to find the solution of three linear equations in three variables.
- // The program does this by calling a function named det3, which recieves the starting address for
- // the 3x3 array and returns the determinant of that array.
- #include<stdio.h>
- #include<stdlib.h>
- #include<math.h>
- // A is a 3*3 matrix
- int det3(int **A)
- {
- 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]);
- return (det);
- }
- void copyAbtoB(int **A, int*b, int **bs, int n)
- {
- int i,j;
- for(i=0;i<3;i++)
- {
- for(j=0;j<3;j++)
- {
- bs[i][j] = A[i][j];
- }
- }
- for(i=0;i<3;i++)
- {
- bs[i][n] = b[i];
- }
- int main()
- {
- int i,j,k;
- int **A = (int**)malloc(sizeof(int*)*3);
- int *b = (int*)malloc(sizeof(int)*3);
- for(i=0;i<3;i++){
- A[i] = (int*)calloc(3,sizeof(int));
- }
- for(i=0;i<3;i++){
- printf("Enter equation %d: ",i+1);
- for(j=0;j<4;j++){
- if(j<3){
- scanf("%d",&A[i][j]);
- }else{
- scanf("%d",&b[i]);
- }
- }
- }
- int det = det3(A);
- if(det == 0){
- printf("System does not have a unique solution because determinant is 0\n");
- }
- else
- {
- int **bs = (int**)malloc(sizeof(int*)*3);
- for(i=0;i<3;i++){
- bs[i] = (int*)calloc(3,sizeof(int));
- }
- int *detB = (int*)calloc(3,sizeof(int));
- for(i=0;i<3;i++){
- copyAbtoB(A,b,bs,i);
- detB[i] = det3(bs);
- }
- float x = (detB[0]*1.0)/(det*1.0);
- float y = (detB[1]*1.0)/(det*1.0);
- float z = (detB[2]*1.0)/(det*1.0);
- printf("System has unique solution ( %f, %f, %f)\n",x,y,z);
- }
- return(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement