称号:考虑到用户层面。打印出指定的矩阵,例如,一个给定的用户10,例如,下面的输出应被视为在图:
程序如下所示:
#include#include int main(){ int dimension; int *p; int startx, starty, endx, endy; int i, j, value = 0; printf("Please input dimension:"); scanf("%d", &dimension); p = (int *)malloc(sizeof(int)*dimension*dimension); startx = 0; starty = 0; endx = dimension - 1; endy = dimension - 1; while(startx <= endx) { if(startx == endx) //仅仅剩一个点须要赋值 { p[endy*dimension+endx] = value++; break; } for(i = starty, j = startx; i <= endy; i++) //从上到下 { p[i*dimension+j] = value ++; } for(i-=1, j = startx+1; j <= endx; j++) //从左到右, i在从上到下的输入中已经超出了矩阵范围,所以须要减1 { p[i*dimension+j] = value++; } for(j-=1, i -= 1; i >= starty; i--) //从下到上 { p[i*dimension+j] = value++; } for(i+=1, j -= 1; j > starty; j--) //从右到左 { p[i*dimension+j] = value++; } startx ++; starty ++; endx --; endy --; } for(i = 0; i < dimension*dimension; i++) { if(0 == i%dimension) printf("\n"); printf("%3d ", p[i]); } printf("\n\n"); return 0; }
程序执行结果:
版权声明:本文博客原创文章。博客,未经同意,不得转载。