在c ++中找到3 * 3矩阵的行列式

时间:2011-03-14 13:53:28

标签: c++ pointers

大家好我想用c ++找到3X3矩阵的行列式我写了下面的代码,但它不起作用。有人可以指出这个bug吗? 提前致谢

#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;
}

1 个答案:

答案 0 :(得分:0)

我建议在那里放一些调试来尝试找出'2'的来源。例如:

#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;
}

...格式更清晰,应该有助于确定问题的来源。