关于行列式计算的一段代码的问题
Issue with a piece of code regarding the calculation of a determinant
我写了一段代码,用来计算行列式,在过去的两个小时里,我一直在查看代码,不确定错误的确切位置。我愿意接受任何批评和提示。这是代码:
#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...
循环之外(对此不太确定,所以请仔细检查)。
相关文章:
- 如何为一段代码启用 -permissive
- 使用Qt Creator在调试模式下编译一段代码
- 防止一段代码在协程中并发执行
- 通过创建单个线程来运行一段代码可加快执行速度
- 有没有一种标准方法来确保一段代码在全局范围内执行
- C++函数 Sleep() 在一段代码之前执行
- C++中的继承和模板:为什么以下一段代码不编译?
- 一段C++代码出现错误"invalid pointer"
- 我必须编写一段代码,基本上执行c++中的strlen()函数,哪里出了问题
- 关于行列式计算的一段代码的问题
- 将两个或多个互斥体应用于一段代码
- 使类使用浮点数和整数(分析一段代码)
- 如何在C++中编写一段代码以查找系统路径上文件的完整路径
- 从第二次调用开始在函数中执行一段代码
- 将一段C++代码封装到Python中
- 解释一段c++代码
- 了解CHIP8模拟器中的一段代码
- 将一段代码从c++转换为c#
- 如何只执行一段代码一次
- 如何对依赖于Asio的一段代码进行单元测试