开发者

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++){
        fo开发者_StackOverflow社区r(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜