我从NxM矩阵中得到一个2x2矩阵。在此之后,我需要找到它的行列式和逆矩阵,然而,在for循环之外,2x2矩阵似乎全部被删除了,而不是作为变量保存在struct matrix
中,我打算在其中存储它。我不知道自己做错了什么,因为我是个初学者。新的2x2矩阵m2
似乎没有显示任何内容。请注意,矩阵元素是从文件中获得的。
void matrixDeterminant(struct Matrix mat, struct Matrix *m2)
{
int mrow = 0;
int mcol = 0;
/********************************************************/
// NEW EDIT
(*m2).rows = 2;
(*m2).cols = 2;
printf("Finding determinant\n");
printf("Enter row to start the 2x2 matrix:\n");
scanf("%d", &mrow);
printf("Enter column to start the 2x2 matrix:\n");
scanf("%d", &mcol);
//deducing a new matrix
for(int i = mrow; i <= mrow+1; i++)
{
printf("Row %d: ", i-2);
for(int j = mcol; j <= mcol+1; j++)
{
// defining a new 2x2 matrix
(*m2).Matrix[i][j] = (mat).Matrix[i-1][j-1];
printf("\t%.2f",(*m2).Matrix[i][j]);
}
printf("\n");
}
}
the Output:
Enter one character name of the matrix, e.g, A, B etc:
A
Enter # rows of matrix (<10):
5
Enter # columns of matrix (<10):
5
Matrix A:
The matrix is:
Row 1: 2.00 4.00 2.00 4.00 1.00
Row 2: 2.00 -5.00 1.00 10.00 10.00
Row 3: -7.00 10.00 10.00 0.00 6.00
Row 4: -8.00 -2.00 9.00 6.00 10.00
Row 5: 3.00 -10.00 7.00 9.00 4.00
Finding determinant now!
Enter a row where to start the 2x2 matrix:
3
Enter a column where to start the 2x2 matrix:
3
Row 1: 10.00 0.00
Row 2: 9.00 6.00
The matrix is:
发布于 2021-03-16 18:28:08
你忘了为rows
矩阵设置cols
和m2
矩阵.所以它不会被展示。
只需将它们分配到matrixDeterminant
函数中的某个地方:
/*...*/
(*m2).rows = n;
(*m2).cols = n;
/*...*/
更新
在mat
.函数中,您使用嵌套for
中的2个索引(值i
和j
)从矩阵中读取2x2矩阵。问题是,您正在使用相同的索引将它们写入矩阵(这似乎不正确,因为可以使用相同的错误索引打印值),这会导致溢出,因为数据是写在矩阵边界之外的。
我强烈建议您重写for以使其更具可读性,但这并不是绝对必要的,因为您可以(即使不应该)通过添加两个整数并在for中使用/递增它们来解决这个问题:
int y = 0;
for(int i = row; i <= row+1; i++)
{
int x = 0;
printf("Row %d: ", i-2);
for(int j = col; j <= col+1; j++)
{
// defining a new 2x2 matrix
(*m2).Matrix[y][x] = (mat).Matrix[i-1][j-1];
printf("\t%.2f",(*m2).Matrix[y][x]);
x++;
}
printf("\n");
y++;
}
I更喜欢编写下面的修复程序:
/*2x2 sub-matrix*/
void matrixDeterminant(struct matrix mat, struct matrix *m2)
{
int baseRow = 0;
int baseCol = 0;
printf("Finding determinant now!\n");
printf("Enter a row where to start the 2x2 matrix:\n");
scanf("%d", &baseRow);
printf("Enter a column where to start the 2x2 matrix:\n");
scanf("%d", &baseCol);
/*
Since the input is expected to be given in a "human readable" format,
I decrease both 'baseRow' and 'baseCol' so they can be in "program natural" format.
*/
baseRow--;
baseCol--;
(*m2).rows = 2;
(*m2).cols = 2;
for(int i = 0; i < 2; i++)
{
printf("Row %d: ", i+1);
for(int j = 0; j < 2; j++)
{
(*m2).Matrix[i][j] = (mat).Matrix[baseRow+i][baseCol+j];
printf("\t%.2f",(*m2).Matrix[i][j]);
}
printf("\n");
}
}
发布于 2021-03-16 18:29:25
rows
和cols
of m2
没有在matrixDeterminant
中设置,因此没有定义它们。然后,当DisplayMatrix
试图显示矩阵时,不显示值(如果rows
和cols
的值为0,但这不一定总是正确的)。
这可以通过在m2
中指定matrixDeterminant
中的正确尺寸来解决。
m2->rows = 2;
m2->cols = 2;
https://stackoverflow.com/questions/66665363
复制相似问题