gpt4 book ai didi

c - 水平和垂直替换二维数组中的元素

转载 作者:行者123 更新时间:2023-11-30 18:09:08 25 4
gpt4 key购买 nike

下面的代码要求用户输入 2D 数组大小并打印出如下内容:(例如 18x6 网格)

..................
..................
..................
..................
..................
..................

代码从这里开始:

#include <stdio.h>

#define MAX 10

int main()
{
char grid[MAX][MAX];
int i,j,row,col;

printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}

return 0;
}

我现在要求用户提供一个字符串,然后询问他们将其放在哪里,例如:

Please enter grid size: 18 6
Please enter word: Hello
Please enter location: 0 0
Output:
Hello.............
..................
..................
..................
..................
..................
Please enter location: 3 4
Output:
..................
..................
..................
..Hello...........
..................
..................
program just keeps going.

关于如何修改代码有什么想法吗?

PS:垂直似乎很难,但我想先从水平开始,有一些工作要做。

最佳答案

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

#define MAX 10

int main()
{
char grid[MAX][MAX];
int i,j,row, col;
char word[MAX];
int row_w,col_w;
int word_len;

printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);

printf("Please enter word: ");
scanf("%s", word);
word_len = strlen(word);

printf("Please enter location: ");
scanf("%d %d", &row_w, &col_w);

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
}
}

for (j = col_w; j < col_w + word_len; j ++) {
grid[row_w][j] = word[j - col_w];
}

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%c ", grid[i][j]);
}
printf("\n");
}

return 0;
}

关于c - 水平和垂直替换二维数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2742455/

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