【问题标题】:having trouble making a function to find the determinant of a matrix无法创建函数来查找矩阵的行列式
【发布时间】: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] 表示法而不是其指针表示法
  • 不幸的是我不得不使用它
  • 我不会阻止你使用它,但是当你在这里寻求帮助时,想想我们所有人。更好的可读性将吸引更快的帮助。你应该尽可能地简化你的代码。得到答案后,请使用原始代码。
  • 考虑一下当您调用determinanttemp 的样子,以及递归调用将如何解释该数据。
  • @ArdentCoder 是正确的。从可能可行的最愚蠢、最简单的事情开始。利用库和其他支持。一旦你有一个可以运行的简单程序,所有大型应用程序逻辑都是正确的,然后开始添加复杂性以满足较小的需求。

标签: c++ matrix types dynamic-memory-allocation


【解决方案1】:

您对determinantmat 的第一次调用是一个存储在一维数组中的 3x3 矩阵。像这样可视化它:

A B C
D E F
G H I

您创建另一个 3x3 矩阵,temp

填充temp 矩阵的一系列循环排除了第一行和第一列c,所以它第一次看起来像这样:

D E 0
G H 0
0 0 0

这被传递给determinant,它需要一个 2x2 矩阵。既然你已经传递了其他东西,那么递归调用看到的是

D E
0 G

当您构造temp 时,您需要使用较小的矩阵大小,而不是源大小。

【讨论】:

  • 在代码开头将 temp2 定义为 V1 大小的矩阵,在第 80 行添加它,并在递归部分调用 temp2 有效。 for (int i = 0; i &lt; V1; i++) { for (int j = 0; j &lt; V1; j++){ *(temp2 + i * V1 + j) = *(temp + i * rows1 + j); } }
猜你喜欢
  • 2019-11-09
  • 1970-01-01
  • 2021-03-08
  • 2015-05-25
  • 2018-11-10
  • 2020-02-14
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多