目标是获取传入参数的矩阵的转置。
我这样做了,但是没有得到期望的结果:
https://3XXXXXX.io/_oauth/google?close
是矩阵,m
是结果存储的地方
r
当我打印它时,只有第一行被换位并成为第一列。
示例:
void transpose(double m[], size_t rows, size_t cols, double r[])
{
for (size_t i = 0; i < rows; i += 1)
{
for (size_t j = 0; j < cols; j += 1)
{
r[j * cols + i] = m[i * rows + j];
}
}
}
将是:
1 2
3 4
但使用我的代码:
1 3
2 4
给我:
1 2
3 4
答案 0 :(得分:0)
此行
r[j * cols + i] = m[i * rows + j];
是错误的。尝试:
r[j * rows + i] = m[i * cols + j];
因为它是给出行之间距离的列数。
答案 1 :(得分:0)
正如我在评论中所述以及在4386427的答复中所述,您的映射错误。
演示:
#include <stdio.h>
#define ROW (2)
#define COLUMN (3)
void transpose(double m[], size_t rows, size_t cols, double r[])
{
for (size_t i = 0; i < rows; i += 1)
{
for (size_t j = 0; j < cols; j += 1)
{
printf("i = %zu, j = %zu --- Interchanging %lf with %lf\n", i, j, r[j * rows + i], m[i * cols + j]);
r[j * rows + i] = m[i * cols + j];
}
}
}
int main(void)
{
double m[ROW*COLUMN] = { 1, 2, 3, 4, 5, 6 };
double n[COLUMN*ROW] = { 7, 8, 9, 10, 11, 12 };
/*
* m -> 1 2 3
* 4 5 6
*
* n -> 7 8
* 9 10
* 11 12
*/
transpose(m, ROW, COLUMN, n);
printf("\nTranspose of matrix m is (in 1D form):\n");
for(int i = 0; i < ROW*COLUMN; i++)
{
printf("%lf ", n[i]);
}
printf("\n");
return 0;
}
我也初始化了第二个矩阵,以查看哪个数字到达哪里。
输出:
[root@localhost little_programs]# gcc -Wall -std=c99 -o matrix_T matrix_T.c
[root@localhost little_programs]# ./matrix_T
i = 0, j = 0 --- Interchanging 7.000000 with 1.000000
i = 0, j = 1 --- Interchanging 9.000000 with 2.000000
i = 0, j = 2 --- Interchanging 11.000000 with 3.000000
i = 1, j = 0 --- Interchanging 8.000000 with 4.000000
i = 1, j = 1 --- Interchanging 10.000000 with 5.000000
i = 1, j = 2 --- Interchanging 12.000000 with 6.000000
Transpose of matrix m is (in 1D form):
1.000000 4.000000 2.000000 5.000000 3.000000 6.000000
仔细检查循环的每个步骤中发生了什么,您会发现出了什么问题。