题目:用户给定一个维度,打印出指定的一个矩阵,例如用户给定10,输出应该如下图所示:
程序如下:
#include <stdio.h> #include <malloc.h> 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; }
程序运行结果:
输入一个维度,逆时针打印出一个指定的矩阵,布布扣,bubuko.com
原文地址:http://blog.csdn.net/laoniu_c/article/details/38085767