【发布时间】:2018-11-04 19:07:48
【问题描述】:
我正在编写一段使用结构和 5 个预定义函数的代码,我在将所选索引处的输入二维数组的值传递给新的二维数组时遇到问题。
我已经包含了我的函数和我遇到困难的函数的代码。
struct matrix
{
char name;
int mValues[10][10];
int ncols;
int nrows;
};
void matrixInput(struct matrix *matA);
void matrixDisplay(struct matrix matA);
void matrixTrace(struct matrix matA, int *trace);
void matrixDeterminant(struct matrix m1, struct matrix *m2, int * determinant);
///function body
void matrixDeterminant(struct matrix m1, struct matrix *m2, int * determinant)
{
int i, j, k, l;
FILE* fin;
fin = fopen("marks.txt", "r");
if(((m1.nrows)>2))
{
printf("\n\nFinding the deterinamt now.\n");
if(fin!=NULL)
{
do
{
printf("Please assign a letter to name your matrix A - Z : ");
scanf(" %c", &((*m2).name));
}
while((((*m2).name)<'A') || ((*m2).name)>'Z');
do
{
printf("\n\nEnter the row where you want to start the 2x2 matrix.\nNumber needs to be between 1 and %d : ", ((m1).nrows-1));
scanf("%d", &k);
}
while((k) >= ((m1).nrows));
do
{
printf("\n\nEnter the column where you want to start you 2x2 mtrix.\nNumber needs to be between 1 and %d : ", ((m1).ncols-1));
scanf("%d", &l);
}
while((l) >= ((m1).ncols));
}
for(i=0; i<2; i++,k++)
{
printf("Row %d:\t", i+1);
for(j=0; j<2; j++,l++)
{
((*m2).mValues[i][j]) = ((m1).mValues[k-1][l-1]);
printf("%d\t",((*m2).mValues[i][j]));
}
printf("\n");
}
}
/// Input/Output
Please assign a letter to name your matrix A - Z : H
Please enter the number of rows in matrix H > 1 < 10 :8
Please enter the number of cols in matrix H > 1 < 10 :8
Matrix H has 8 rows and 8 columns and contains:
Row 1: 55 7 40 30 32 45 43 77
Row 2: 72 1 20 65 85 40 46 22
Row 3: 45 77 88 32 30 55 59 99
Row 4: 72 37 33 18 44 73 44 12
Row 5: 88 2 11 55 7 40 30 32
Row 6: 24 73 13 99 99 22 45 77
Row 7: 88 32 22 11 98 34 38 37
Row 8: 33 18 44 73 22 45 77 88
Trace of matrix H = 317
Finding the deterinamt now.
Please assign a letter to name your matrix A - Z : F
Enter the row where you want to start the 2x2 matrix.
Number needs to be between 1 and 7 : 3
Enter the column where you want to start you 2x2 mtrix.
Number needs to be between 1 and 7 : 3
Row 1: 88 32
Row 2: 44 73 // This has shifted 2 columns.
Process returned 0 (0x0) execution time : 14.807 s
Press ENTER to continue.
First 函数允许用户命名并定义矩阵的维度,然后从包含 10x10 整数的 .txt 文件中填充该矩阵。
第二个函数显示矩阵,第三个函数计算迹线。
第四个函数要求用户选择一个 2x2 矩阵,它是原始矩阵的子集。 2x2 矩阵的内容必须连同其名称和大小一起存储在一个新的结构矩阵中。
我“认为”我所做的是询问用户从哪里开始子矩阵并将值存储在 k 和 l 处,然后我将这些值用作索引。
我认为我的问题发生的地方是将这些值传递给新矩阵,在嵌套的 for 循环中,我增加了 i 和 j 来索引新矩阵,并增加 l 和 k 来索引我从中传递值的矩阵。
注意:我以前从未见过在 for 循环中增加 2 个值,所以我希望它没有做我“认为”它正在做的事情,因为子矩阵的第 2 行已经移动了 2 列。
任何帮助将不胜感激。
【问题讨论】:
-
题外话:小写的“L”不是变量名最快乐的选择。它们太容易与数字 1 混淆。如果您不本能地避免这种选择,那么您将在未来为一个困难的调试会话做好准备。
-
@JohnColeman 感谢您的建议,我会牢记前进。
-
struct matrix m1, struct matrix *m2似乎不一致。为什么其中一个参数是指针而另一个不是? -
@JohnColeman 我认为问题在于我在嵌套的 for 循环中传递值的方式,子矩阵的第 2 行是 +2 列到我试图获取它的位置。我已经包含了函数和函数体以尝试尽可能具体,我对编程不是很有经验,所以如果我的问题模棱两可,我深表歉意。
-
@JohnColeman 这些功能是预先确定的,所以我别无选择,只能按照声明使用它们。
标签: c function pointers multidimensional-array