简体   繁体   中英

To find determinant of a 3*3 matrix in c++

hi guys I wanted to find determinant of a 3X3 matrix using c++ I wrote the following code but its not working. Can someone please point out the bug? Thanks in advance

#include<iostream>
#include<cstdlib>
#include<fstream>

using namespace std;
#define R 3

int main(){
    fstream f;
    int x=1;
    f.open("values");//open the file that contains the matrix
    int** A;
    A=new int*[R];
    for(int i=0;i<R;i++){
        A[i]=new int[R];
    }
    for(int i=0;i<R;i++){
        for(int j=0;j<R;j++){
            f>>A[i][j];//input values
        }
    }
    for(int i=0;i<R;i++){
        x=x*A[i][i];
        for(int j=0;j<R;j++){   
            if(A[i][i]!=0){A[i][j]=A[i][j]/A[i][i];}//using Gauss Jordan Elimination method
        }
        for(int k=i+1;k<R;k++){//going at the next row...basically sweeping a column
            for(int y=i;y<R;y++){
                A[k][y]=A[k][y]-(A[k][i]*A[i][y]);//sweeping
            }           
        }
    }
    f.close();
    int z=1;
    for(int i=0;i<R;i++){
        z=z*A[i][i];//in case all a[i][i] are zero z will be zero and hence the answer
    }
    cout<<"The det  is"<<endl<<x*z<<endl;
    return 0;
}

I would suggest putting some debug in there to try and work out where your '2' is coming from. For example:

#include<iostream>
#include<cstdlib>
#include<fstream>

using namespace std;

#define R (3)

int main(){
    fstream f;
    int x=1;
    f.open("values");//open the file that contains the matrix

    // Assign and populate A
    int** A = new int*[R];
    for(int i=0;i<R;i++){
        A[i]=new int[R];
    }
    f.close();

    // Show what we started with
    for(int i=0;i<R;i++){
        for(int j=0;j<R;j++){
            f>>A[i][j];//input values
            printf("[%04d] ",A[i][j]);
        }
        printf("\n");
    }

    // Find the determinant
    for(int i=0;i<R;i++){
        x=x*A[i][i];
        for(int j=0;j<R;j++){
            if(A[i][i]!=0){
                A[i][j]=A[i][j]/A[i][i];
            }//using Gauss Jordan Elimination method
        }
        for(int k=i+1;k<R;k++){
            for(int y=i;y<R;y++){
                A[k][y]=A[k][y]-(A[k][i]*A[i][y]);
            }           
        }
    }

    // Show the resulting matrix
    for(int i=0;i<R;i++){
        for(int j=0;j<R;j++){
            f>>A[i][j];//input values
            printf("[%04d] ",A[i][j]);
        }
        printf("\n");
    }       

    int z=1;
    for(int i=0;i<R;i++){
        z=z*A[i][i];
    }
    cout<<"x is"<<endl<<x;<<endl<<"z is"<<endl<<z;<<endl;
    cout<<"The det  is"<<endl<<x*z;<<endl;
    return 0;
}

...is more clearly formatted and should help identify where the problem is coming from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM