【发布时间】:2020-09-20 16:59:21
【问题描述】:
我一直在尝试编写一个程序来显示稀疏矩阵并找到矩阵的转置,但是在转置时,只有原始矩阵第一行的元素被转置,所有其他元素都来自其他行被忽略。我需要一些帮助。
这是我写的代码
#include <stdio.h>
#include <stdlib.h>
struct Element{
int i;
int j;
int x;
};
struct Sparse{
int m;
int n;
int num;
struct Element *ele;
};
void create(struct Sparse *s){
printf("Enter the dimensions ");
scanf("%d%d",&s->m, &s->n );
printf("Number of non-zero elements");
scanf("%d",&s->num);
s-> ele= (struct Element*) malloc(s->num * sizeof(struct Element));
printf("Enter all non-zero elements\n");
for (int i = 0; i< s->num; i++)
{
scanf("%d%d%d",&s->ele[i].i,&s->ele[i].j,&s->ele[i].x);
}
}
void display(struct Sparse s){
int i,j,k=0;
for (i = 0; i < s.m; i++)
{
for (j = 0; j < s.n; j++)
{
if(i==s.ele[k].i && j== s.ele[k].j)
printf("%d ",s.ele[k++].x);
else
printf("0 ");
}
printf(" \n");
}
}
void createTranspose(struct Sparse *t, struct Sparse s){
t->m = s.n;
t->n = s.m;
t->num = s.num;
t-> ele= (struct Element*) malloc(t->num * sizeof(struct Element));
printf("Enter all non-zero elements\n");
for (int i = 0; i< t->num; i++)
{
t->ele[i].i= s.ele[i].j;
t->ele[i].j= s.ele[i].i;
t->ele[i].x= s.ele[i].x;
}
}
int main(){
struct Sparse s, t;
create(&s);
display(s);
createTranspose(&t,s);
printf("Transpose of the matrix is \n");
display(t);
return 0;
}
输出
Enter the dimensions 6 6
Number of non-zero elements6
Enter all non-zero elements
0 0 1
0 2 2
0 4 3
2 3 4
4 1 5
5 5 6
1 0 2 0 3 0
0 0 0 0 0 0
0 0 0 4 0 0
0 0 0 0 0 0
0 5 0 0 0 0
0 0 0 0 0 6
Enter all non-zero elements
Transpose of the matrix is
1 0 0 0 0 0
0 0 0 0 0 0
2 0 0 0 0 0
0 0 0 0 0 0
3 0 0 0 0 0
0 0 0 0 0 0
我们将非常感谢您对获得正确输出的帮助。
【问题讨论】:
-
这个bug在你的显示函数中。
标签: c matrix sparse-matrix