救急!
我只学到指针,咋写啊? 要求用C语言? #include <stdio.h>
#include <stdlib.h>
int main()
{
printf("请输入方针阶数:");
int n,k,i,j;
int i_add = 1, j_add = 1;
int mode = 1;//mode代表模式,1为横向移动,0为纵向移动
scanf("%d", &n);
//动态申请n*n大小的内存
int **arr = (int**)malloc(sizeof(int*)*n);
for (k = 0; k < n; k++)
arr = (int*)malloc(sizeof(int*)*n);
//初始化n*n方针
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
arr = 0;
//重置i,j变量
i = 0; j = 0; k = 1;//i代表行,j代表列,k用来递增
while (k <= n*n)
{
if (mode == 0)
{
arr = k++;
i += i_add;
if (i < n&&i >= 0 && arr == 0);//正常情况不做处理
else//超出边界或者已经有数
{
i -= i_add;//回退
i_add = -i_add;
mode = 1;
j += j_add;
}
}
if (mode == 1)
{
arr = k++;
j += j_add;
if (j < n&&j >= 0 && arr == 0);//正常情况不做处理
else//超出边界或者已经有数
{
j -= j_add;//回退
j_add = -j_add;
mode = 0;
i += i_add;
}
}
}
//打印
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%5d ", arr);
printf("\n");
}
//释放内存
for (k = 0; k < n; k++)
free(arr);
free(arr);
} 有点无脑{:5_109:} #include <stdio.h>
#include <stdlib.h>
typedef struct move_direction {
int x;
int y;
struct move_direction *next_direction;
}dir;
int main()
{
//定义移动的四个方向
dir down, up, left, right;
//定义当前的方向
dir *now_dir = &right;
down.x = 1;down.y = 0; down.next_direction = &left;
up.x = -1; up.y = 0; up.next_direction = &right;
left.x = 0; left.y = -1; left.next_direction = &up;
right.x = 0; right.y = 1; right.next_direction = &down;
printf("请输入方针阶数:");
int n, k, i, j;
int i_add = 1, j_add = 1;
int mode = 1;//mode代表模式,1为横向移动,0为纵向移动
scanf("%d", &n);
//动态申请n*n大小的内存
int **arr = (int**)malloc(sizeof(int*)*n);
for (k = 0; k < n; k++)
arr = (int*)malloc(sizeof(int*)*n);
//初始化n*n方针
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
arr = 0;
//
k = 1; i = 0; j = 0;
while (k <= n * n)
{
arr = k++;
i += (*now_dir).x;
j += (*now_dir).y;
if (j < n&&j >= 0&&i<n&&i>=0 && arr == 0);//正常情况不做处理
else//超出边界或者已经有数
{
//回退
i -= (*now_dir).x;
j -= (*now_dir).y;
now_dir = now_dir->next_direction;
i += (*now_dir).x;
j += (*now_dir).y;
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%5d ", arr);
printf("\n");
}
} 法二,还是有点笨{:5_99:} 1005204767 发表于 2018-12-5 23:34
要求用C语言?
对啊 螺旋阵最后一个输出1? lemon3 发表于 2018-12-6 14:55
螺旋阵最后一个输出1?
可能题出错了,16才合理一些 嗯 1005204767 发表于 2018-12-6 15:17
可能题出错了,16才合理一些
漏掉了个6哈哈哈
页:
[1]