gpt4 book ai didi

c - 为什么随机值显示为输出以查找矩阵的行列式?

转载 作者:行者123 更新时间:2023-12-04 10:15:27 25 4
gpt4 key购买 nike

我想通过使用 找到 M*M 矩阵的行列式递归 C .
这是我在 Ubuntu 中尝试过的代码。

// Computing determinant of a MXM matrix

#include <stdio.h>

int determinant(int M, int A[10][10]) { //Function to calculate det(A)
int i, j, k, m, n, p, q, pow = 1;
int B[10][10];//assuming M does not cross 10
if (M == 1)
return A[0][0];
else {
det = 0;
for (k = 0; k < M; k += 1) {
m = 0;
n = 0; //m,n are indices of subdeterminant of A
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
if (i != 0 && j != k) {
B[m][n] = A[i][j]; //finding submatrix
if (n < (k - 2))
n += 1;
else {
n = 0;
m += 1;
}
}
}
}
det += pow * (A[0][k] * determinant(M - 1, B));
pow = -1 * pow;
}
return det;
}
}

int main() {
int M, i, j; // M is order of matrix A for which determinant has to be found
printf("Enter the order of matrix: ");
scanf("%d", &M);
int A[10][10];
printf("Enter matrix A: ");
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
scanf("%d", &A[i][j]); //Entering elements of matrix A
}
}
printf("Given matrix A is: \n");
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
printf("%d ", A[i][j]);
}
printf("\n");
}
int det = determinant(M, A);
printf("The determinant of given matrix is %d\n", det);
return 0;
}

此代码适用于 2 阶矩阵。但对于更高阶的矩阵,输出是一些随机数。我无法确定这有什么错误。谁能解释为什么输出不符合预期以及如何纠正代码以获得预期输出?

最佳答案

提取子矩阵的内循环B来自 A似乎坏了。

这是一个更简单的版本:

        for (i = 1, m = 0; i < M; i++, m++) {
for (j = 0, n = 0; j < k; j++, n++)
B[m][n] = A[i][j];
for (j = k + 1; j < M; j++, n++)
B[m][n] = A[i][j];
}

关于c - 为什么随机值显示为输出以查找矩阵的行列式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61083068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com