gpt4 book ai didi

c - 甚至以向后方式排列数组的字符串

转载 作者:行者123 更新时间:2023-11-30 18:49:56 27 4
gpt4 key购买 nike

我正在尝试打印一个数组,以便向后打印偶数字符串,但以通常的方式打印非偶数字符串。我做错了什么?例如:

1 0 3
9 7 3
5 7 8

我需要它:

1 0 3
3 7 9
5 7 8

但是我也遇到了以螺旋方式填充数组的问题;我应该如何取数组的中心?请您提供一个想法——我该怎么做?并且数组必须是正方形的。例如:

1 2 3
4 5 6
7 8 9

但我需要它:

3 2 9
4 1 8
5 6 7

到目前为止我的代码:

#include <stdio.h>
#include <stdlib.h>


int main()
{
int a[10][10],n,m,i,j;

printf("Enter m: ");
scanf("%d",&m);
printf("Enter n: ");
scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("a[%d][%d]: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}

// in usual order
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}


for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(i%2 != 0){
printf("%d ",a[i][j]);
}
else {
printf("%d ",a[n-i+1][j]);
}
}
printf("\n");
}

return 0;
}

最佳答案

螺旋填充数组的示例

#include <stdio.h>
#include <string.h>

typedef enum {
N, W, S, E
} Dir;

typedef struct walker {
int row, col;
Dir dir;
int steps;
} Walker;

Walker go_forward(Walker walker){
switch(walker.dir){
case N:
walker.row -= 1;
break;
case W:
walker.col -= 1;
break;
case S:
walker.row += 1;
break;
case E:
walker.col += 1;
break;
}
return walker;
}

Walker proceed_left(Walker walker){
walker.dir = (walker.dir + 1) % 4;//turn left
walker = go_forward(walker);
return walker;
}

int main(void){
int n;
for(;;){
printf("Enter n(0 < n < 10): ");fflush(stdout);
int ret_s = scanf("%d", &n);
if(ret_s == 1){
if(0 < n && n < 10)
break;
} else if(ret_s == 0)
while(getchar() != '\n');//clear input
else //if(ret_s == EOF)
return 0;
}
int a[n][n];
memset(a, 0, sizeof(a));//zero clear
Walker walker = { .row = n / 2, .col = n / 2, .dir = E, .steps = 0 };
for(;;){
walker.steps += 1;
a[walker.row][walker.col] = walker.steps;
if(walker.steps == n * n)//goal
break;
Walker left = proceed_left(walker);
if(a[left.row][left.col] == 0)//left side is vacant
walker = left;
else
walker = go_forward(walker);
}
for(int r = 0; r < n; ++r){
for(int c = 0; c < n; ++c){
if(c)
putchar(' ');
printf("%2d", a[r][c]);
}
puts("");
}
}

关于c - 甚至以向后方式排列数组的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com