Найти определитель матрицы 3 * 3 в c ++ - PullRequest
0 голосов
/ 14 марта 2011

Привет, ребята. Я хотел найти определитель матрицы 3X3, используя c ++. Я написал следующий код, но он не работает.Может кто-нибудь, пожалуйста, указать на ошибку?Заранее спасибо

#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 голосов
/ 14 марта 2011

Я бы посоветовал добавить туда отладку, чтобы попытаться выяснить, откуда исходит ваша '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;
}

... более четко отформатирован и должен помочь определить, откуда возникла проблема.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...