我想转置矩阵的代码工作时,行和当column>row,但当行>列,我得到了错误的答案
所有代码:
#include <stdio.h>
#include <stdlib.h>
int main() {int row,column,tmp;
scanf("%d",&row);
scanf("%d",&column);
int *image=(int*)malloc(sizeof(int)*row*column);
int *target=(int*)malloc(sizeof(int)*row*column);
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
scanf("%d",&tmp);
image[i*column+j]=target[i*column+j]=tmp;
}
}
transpose(row,column,target,image);
for (int i = 0; i< m; i++) {
for (int j = 0; j < n; j++)
printf("%d\t", target[i*column+j]);
printf("\n");
}}
void transpose(int row, int column,int* target,int* image) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
target[j * column + i] = image[i * column + j];
}
}
}我的矩阵在图像中,我想要在目标中转置。
input :
1 2
3 4
5 6
output(what i get from my code) :
1 3 5
5 4 6
output (what should i get ) :
1 3 5
2 4 6
input work :
1 2 3
4 5 6
output :
1 4
2 5
3 6发布于 2021-09-20 08:12:11
正如@Bob_所建议的,您错误地计算了目标数组中的偏移量。
您的源图像有column列和row行;但转置后的图像为row列和column行!(顺便说一句,这是一个糟糕的标识符选择;请考虑将num_columns和num_rows作为转置函数的参数)。所以我认为你需要具备:
target[j * row + i] = image[i * column + j];在你的内部循环中。
发布于 2021-09-20 08:07:24
为了理解你在做什么,我建议你打印你的算法中计算的索引值。
问题是i可以大于column ( j和row也是如此)。你必须使用%来改进你的代码。
https://stackoverflow.com/questions/69250657
复制相似问题