我正在编写代码以从边列表中创建矩阵。
但是,当我运行上述代码时,我得到了一个不在输入数据中的“幻影边缘”,它继续搞砸了我的程序的其余部分。边在矩阵中为9,2,在基本代码形式中为8,1。
矩阵中的所有元素都预先初始化为 0。
这是与矩阵有关的输入数据:
1 2
1 8
2 8
3 5
3 1
4 5
4 6
5 2
5 9
6 4
6 8
7 4
7 10
8 4
8 6
9 4
9 5
10 7
10 3
以下是处理输入的函数:
void displayMatrix(int **matrix, int numberVertices){ //function displays the matrix
int i, j;
for(i=0; i<numberVertices; i++) //go through eveyr element
{
for(j=0; j<numberVertices; j++)
{
printf("%d ", matrix[i][j]); //print element
}
printf("\n");
}
printf("\n\n");
}
void inputMatrix(FILE *fp, int ** matrix) //file places value 1 into matrix if edge exists for the adjacency matrix
{
int e1, e2;
while(!feof(fp)) //continue to the end of the file
{
fscanf(fp, "%d %d", &e1, &e2); //get pairs
e1 = e1 - 1; //adjust the edges for array use
e2 = e2 - 1;
matrix[e1][e2] = 1; //place value 1 into appropriate location in adjacency matrix
}
fclose(fp); //close the file connection
}
0 1 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0 0
1 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 1 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 1 0 0
0 0 0 1 0 0 0 0 0 1
0 0 0 1 0 1 0 0 0 0
0 *1 0 1 1 0 0 0 0 0
0 0 1 0 0 0 1 0 0 0
*不应该存在的条目,不在输入数据中
最佳答案
问题是你比必要的多了一次循环,导致 fscanf
在第一次转换之前失败,从而留下 e1
和 e2
因为它们来自之前的阅读。事实证明,最后一个条目将 e1
设置为 10
,将 e2
设置为 3
,因此 e1
变为 9
并且 e2
变为 2
,从而导致您的幻影边缘。
这个额外循环的原因是因为你的循环条件没有按照你认为的那样去做。 feof
检查是否设置了文件结束标志,这只能在尝试读取文件末尾时设置。因为您在读取文件之前检查文件结尾,所以直到下一次迭代您才真正注意到这一点,因此您循环了额外的时间。正确的修正非常简单;继续直到 fscanf
产生 EOF
。
while (fscanf(fp, "%d %d", &e1, &e2) != EOF)
{
matrix[e1 - 1][e2 - 1] = 1;
}
关于c - 我的列表中的额外优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12453503/