发布一段关于行列式计算的代码

时间:2013-12-16 00:35:43

标签: c++ recursion vector matrix

我编写了一段代码来计算行列式,我花了最后2个小时查看代码,确定错误的确切位置。我对任何批评和提示持开放态度。这是代码:

#include <iostream>
#include <vector>

using namespace std;

int deter(vector < vector<float> >& mm, int vm);

int main () {
    vector< vector<float> > m; //Declaration of the 2D vector
    int vel; //Size of the matrix
    cout << "Unesite velicinu matrice: ";
    cin >> vel;
    m.resize(vel, vector<float> (vel)); //Resizing to the actual size
    for (int i = 0; i < vel; ++i) {
        for (int j = 0; j < vel; ++j) {
            cout << "m[" << i << "][" << j << "]: "; //Input
            cin >> m[i][j];
        }
    }
    cout << "Pregledno ispisana matrica:" << endl;
    for (int i = 0; i < vel; ++i) {
        cout << endl;
        for (int j = 0; j < vel; ++j) {
            cout << m[i][j] << " ";
        }
    }
    cout << "Determinanta vase matrice je: " << deter(m, vel); //Calling the function.
    return 0;
}

int deter(vector < vector <float> >& mm, int vm) { //Passing by reference
    int pr;
    float d = 0;
    vector <float> racun; //Used to recursively call the deter function and save the result
    vector < vector <float> > matri;  //2D Vector
    matri.resize(vm, vector<float> (vm)); //Resizing
    racun.resize(vm);
    if (vm == 2)
        return (mm[0][0] * mm[1][1]) - (mm[0][1] * mm [1][0]); //Case of a 2x2 matrix
    else {
        for (int i = 0; i < vm; ++i) { //Main loop
            int br1 = 0, br2 = 0; //counters
            for (int j = 0; j < vm; ++j) {
                for (int k = 0; k < vm; ++k) {
                    if (j != 0 && k != i) { //Doing the Laplace's expansion, first row.
                        matri[br1][br2] = mm[j][k];
                        ++br2;
                        if (br2 == vm-1){
                            ++br1;
                            br2 = 0;
                        }
                    }
                }
            }
            pr = -1;
            for (int j = 0; j < i; ++j) {
                pr = -1 * pr; //Plus or minus.
            }
            racun[i] = pr * deter(matri, vm-1); //Saving the calculation of each matrix with the ignored row and column
            }
        for (int j = 0; j < vm; ++j) {
            d += mm[0][j] * racun[j]; /*Actual determinant calculation, the mm[0][j] signifies
                                           that it is Laplace's expansion using the first row*/
        }
        return d;
    }
}

为了测试,3x3矩阵的行列式: 1 2 3 4 5 6 7 8 9 应打印出0。 问题是它将核心转储到最后一行。

1 个答案:

答案 0 :(得分:1)

我认为问题可能是您从未为racun向量指定大小,这意味着该行:

 racun[i] = pr * deter(matri, vm-1);

是未定义的行为(有关详细信息,请参阅Setting std::vector contents directly using operator [])。像使用matri之前一样调整大小。

我注意到的另一个问题可能是您的算法存在问题,最后的循环求和d应该在主for (i...循环之外(对此不太确定,所以仔细检查)