[英]obtaining and Storing a Struct 2D array or matrix from a void function
我从 NxM 矩阵中获得一个 2x2 矩阵。 在此之后,我需要找到它的行列式并因此找到逆矩阵,但是 2x2 矩阵似乎只是在 for 循环之外一起被删除,而不是作为变量保存在我打算存储它的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:
您cols
为m2
矩阵设置rows
和列...所以它不会显示。
只需将它们分配到matrixDeterminant
function 内的某个位置:
/*...*/
(*m2).rows = n;
(*m2).cols = n;
/*...*/
在matrixDeterminant
function 中,您在嵌套for
中使用 2 个索引(值i
和j
)从矩阵mat
读取2x2 矩阵。 问题是您使用相同的索引将它们写入m2
矩阵(这似乎不正确,因为您可以使用相同的错误索引打印值),导致溢出,因为数据写入矩阵边界之外。
我强烈建议您重写 for 以使其更具可读性,但这并不是绝对必要的,因为您可以(即使您不应该)通过添加 2 个整数并在 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++;
}
我更喜欢下面写的修复:
/*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");
}
}
m2
的rows
和列未在cols
中设置, matrixDeterminant
它们未定义。 然后,当DisplayMatrix
尝试显示矩阵时,不会显示任何值(如果rows
和cols
的值为 0,但不一定总是如此)。
这可以通过在matrixDeterminant
中为m2
分配正确的维度来解决:
m2->rows = 2;
m2->cols = 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.