C语言之矩阵转置/纵横变换
转置前:
[liangjian@localhost ~]$ cat test18.c
#include <stdio.h>
int main()
{
int a[4][5]=
{
{45, 56, 77, 88, 99},
{67, 77, 85, 89, 99},
{66, 77, 94, 86, 99},
{78, 93, 90, 67, 99}
};
//int a[3][]={1,2,3,4,5,6,7,8,9,10,11,12}; //只有第一维度可以省略不写(这里的3可以省略不写),4必须写,3和4不能同时不写。
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf("%d ",a[i][j]); //%d后面的空格,控制下面输出的45,56等之间的空格。
}
printf("\n");
}
}
[liangjian@localhost ~]$ gcc test18.c &&./a.out
45 56 77 88 99
67 77 85 89 99
66 77 94 86 99
78 93 90 67 99
[liangjian@localhost ~]$
转置方法:i的条件和j的条件互换即可。
转置实例及执行结果展示:
[liangjian@localhost ~]$ cat test18.c
#include <stdio.h>
int main()
{
int a[4][5]=
{
{45, 56, 77, 88, 99},
{67, 77, 85, 89, 99},
{66, 77, 94, 86, 99},
{78, 93, 90, 67, 99}
};
//int a[3][]={1,2,3,4,5,6,7,8,9,10,11,12}; //只有第一维度可以省略不写(这里的3可以省略不写),4必须写,3和4不能同时不写。
int i,j;
for(i=0;i<5;i++) //i<4变为i<5。
{
for(j=0;j<4;j++) //j<5变为j<4。
{
printf("%d ",a[j][i]); //i,j互换位置。
}
printf("\n");
}
return 0;
}
[liangjian@localhost ~]$ gcc test18.c &&./a.out
45 67 66 78
56 77 77 93
77 85 94 90
88 89 86 67
99 99 99 99
[liangjian@localhost ~]$