【发布时间】:2020-07-17 21:25:32
【问题描述】:
可能是一个简单的解决方法,但我一直得到 0 作为我应该得到 22 的确定值,我也必须使用动态内存分配。使用浮点数可能会出现一些问题,因为我并不完全熟悉它们如何使用指针。老实说,不知道是什么导致函数输出零。
cpp.sh 测试链接:http://cpp.sh/5bu2v
#include <iostream>
#include <math.h>
using namespace std;
float determinant(float *mat1, int &rows1)
{
float s = 1, D = 0;
float *temp = new float[rows1 * rows1];
int i, j, m, n, c;
if (rows1 == 1)
{
return (*(mat1 + 0 * rows1 + 0));
}
else
{
D = 0;
for (c = 0; c < rows1; c++)
{
m = 0;
n = 0;
for (i = 0; i < rows1; i++)
{
for (j = 0; j < rows1; j++)
{
*(temp + i * rows1 + j) = 0;
if (i != 0 && j != c)
{
*(temp + m * rows1 + n) = *(mat1 + i * rows1 + j);
if (n < (rows1 - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
int V1 = rows1 - 1;
D = D + s * (*(mat1 + 0 * rows1 + c) * determinant(temp, V1));
s = -1 * s;
}
}
return (D);
}
int main()
{
int i, j;
int n = 3;
int matrix[10][10] = {{1, 2, 3},
{0, 4, 5},
{1, 0, 6}};
float *mat1 = new float[n * n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
*(mat1 + i * n + j) = matrix[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
cout << "Determinant of the matrix is " << determinant(mat1, n);
return 0;
}
【问题讨论】:
-
为了便于阅读,请使用
arr[i][j]表示法而不是其指针表示法 -
不幸的是我不得不使用它
-
我不会阻止你使用它,但是当你在这里寻求帮助时,想想我们所有人。更好的可读性将吸引更快的帮助。你应该尽可能地简化你的代码。得到答案后,请使用原始代码。
-
考虑一下当您调用
determinant时temp的样子,以及递归调用将如何解释该数据。 -
@ArdentCoder 是正确的。从可能可行的最愚蠢、最简单的事情开始。利用库和其他支持。一旦你有一个可以运行的简单程序,所有大型应用程序逻辑都是正确的,然后开始添加复杂性以满足较小的需求。
标签: c++ matrix types dynamic-memory-allocation