关于行列式计算的一段代码的问题

Issue with a piece of code regarding the calculation of a determinant

本文关键字:一段 代码 问题 行列式 计算      更新时间:2023-10-16

我写了一段代码,用来计算行列式,在过去的两个小时里,我一直在查看代码,不确定错误的确切位置。我愿意接受任何批评和提示。这是代码:

#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 34 5 67 8 9应打印出0。问题是它将核心转储到最后一行。

我认为问题可能是您从未为racun矢量分配大小,这意味着行:

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

是未定义的行为(有关更多详细信息,请参阅直接使用运算符[]设置std::vector内容)。像使用matri一样调整大小。

我注意到的另一件事可能是你的算法有问题,那就是末尾的循环求和d应该在主for (i...循环之外(对此不太确定,所以请仔细检查)。