我目前正在做一个添加稀疏矩阵的问题。我正在使用三元组形式制作稀疏矩阵。三元组形式是通过使用 c 中的结构制成的。
struct sparse
{
int row;
int col;
int val;
};
但是在做这个稀疏矩阵问题时,我遇到了一个问题,即当我按递增顺序给出非零值的索引时,我的代码只显示正确的稀疏矩阵(例如 (0 1 3),(1 2 5),(2 2 7) 等) 否则它显示不正确的矩阵。例如,如果我给出像 (0 1 3),(2 2 7),(1 2 5) 等输入,那么它显示错误的矩阵。如何解决这个问题,以便以任何索引顺序给出正确的输出?
我已经添加了我的输入和结果输出。我已经为两个稀疏矩阵做了这个。
#include<iostream>
#include<cstdio>
struct sparse
{
int row,col,val;
};
void readmat(sparse sp[])
{
printf("enter total number number of rows ,column of matrix and total
of nonzero values in this\n");
scanf("%d %d %d",&sp[0].row,&sp[0].col,&sp[0].val);
printf("now start entering the values by specifying index
position\n");
for(int i=1;i<=sp[0].val;i++)
scanf("%d %d %d",&sp[i].row,&sp[i].col,&sp[i].val);
}
void displaymat(sparse sp[])
{
int k=1;
for(int i=0;i<sp[0].row;i++)
{
for(int j=0;j<sp[0].col;j++)
{
if(k<=sp[0].val&&i==sp[k].row&&j==sp[k].col)
{
printf("%d\t",sp[k].val);
k++;
}
else
printf("0\t");
}
printf("\n");
}
}
int main()
{
struct sparse sp1[10],sp2[10],sp3[10];
printf("for first matrix\n");
readmat(sp1);
printf("for second matrix\n");
readmat(sp2);
displaymat(sp1);
printf("\n\n");
displaymat(sp2);
printf("\n\n");
displaymat(sp3);
return 0;
}`
更新原始答案:
乱序值没有被打印的原因是因为当三元组形式的值指向更向下的元素时,for 循环会超过所有其他可以打印的值。例如,在您的示例中,第三个元素位于 row=1, col=3 处,但是第二个元素位于 row=2,col=2 处。这将导致外部 for 循环向下推进到第 2 行。在那个时间点,循环不会返回并打印第一行。
一种方法是根据行和列进行排序,然后打印值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句