我编了这个程序,得到了矩阵a
和矩阵b
,这是矩阵a
的转置矩阵.
问题是我不能得到一个准确的换位矩阵.
我判断了几次功能,但都找不到哪一部分错了.
编译时没有出现错误.
#include <stdio.h>
typedef struct
{
int row;
int col;
int value;
} term;
我声明了我在整个程序中使用的 struct term.
void transpose(term a[], term b[])
{
int n, currentb;
n = a[0].value; // Total number of elements
b[0].row = a[0].col; // Number of rows in b = Number of columns in a
b[0].col = a[0].row; // Number of columns in b = Number of rows in a
b[0].value = n;
if (n > 0) // A nonzero matrix
{
currentb = 1;
for (int i = 0; i < a[0].col; i++) // Starting from the 0th column
{
for (int j = 1; j <= n; j++) // Find the element from the current column
{
if (a[j].col == i)
{
// Add the elements in the current column to b.
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}
}
}
}
起初,我认为上面的函数是错误的.
所以,我已经看了几次逻辑,我找不到错误的部分.
int main()
{
term a[3] = { {1,2,3}, {4,5,6}, {7,8,9} }
term b[3];
// print term a
printf("original matrix\n");
for (int i = 0; i < 3; i++)
{
printf(" %d %d %d\n", a[i].row, a[i].col, a[i].value);
}
printf("\n\n");
// call the transpose function
void transpose(term a[], term b[]);
// print term b
printf("transpose matrix\n");
for (int i = 0; i < 3; i++)
{
printf(" %d %d %d\n", b[i].row, b[i].col, b[i].value);
}
return 0;
}
接下来,我查看了调用转置函数的代码行.
因为输出结果是这样的:
original matrix
1 2 3
4 5 6
7 8 9
transpose matrix
-858993460 -858993460 -858993460
-858993460 -858993460 -858993460
-858993460 -858993460 -858993460
我已经搜索了超过10页的问题,但我还没有找到像我这样使用 struct 来获得换位矩阵的错误结果的问题.
如果代码没有问题,结果应该如下所示.
original matrix
1 2 3
4 5 6
7 8 9
transpose matrix
1 4 7
2 5 8
3 6 9
请判断我的代码,如果你能告诉我有什么问题,我将不胜感激.