gpt4 book ai didi

c - 如何用C语言画一个不同符号和对角线的正方形?

转载 作者:行者123 更新时间:2023-11-30 20:57:29 34 4
gpt4 key购买 nike

伙计们,我被困在这里了。我正在尝试学习 c 并创建一些非常基本的代码,要求用户插入数字。然后,这个数字输入下面的公式:2x+1,然后我想让它打印一个空心的正方形图案,行和列有不同的符号,并在角、对角线处添加一个+,在中间添加一个“X” .

我陷入了代码的最开头。我不知道我应该从哪里开始。我的意思是我什至无法学习如何为行和列制作不同的符号。

我已经尝试学习和研究了 3 个小时,观看了 20 个不同的 YouTube 视频并阅读了 20 个不同的编码指南。真是郁闷啊..

谢谢。

我附上了我的代码和输出的图片,以及右侧所需的输出。 enter image description here

代码本身:

int size;
printf("Please enter a number that will define the size of the square: \n");
scanf("%d", &size);
size = 2 * size + 1;
for (int i = 1; i <= size-2; i++) {
for (int j = 1; j <= size-2; j++) {
if (j == 1 || j == size - 1) {
printf("|");
}
else {
printf(" ");
}
if (i==1 || i==size-2){
printf("-");
}
else {
printf(" ");
}
}

printf("\n");
}

最佳答案

#include <stdio.h>

int main(void) {
int size;
printf("Please enter a number that will define the size of the square: \n");
scanf("%d", &size);
size = 2 * size + 1;

const char *spaces=" ";
const char *dashes="-----------------------------------------";

printf("+%.*s+\n", size, dashes);
for(int i=1; i<size/2+1; ++i)
{
printf("|%.*s\\%.*s/%.*s|\n", i-1, spaces, size-2*i, spaces,i-1, spaces);
}

printf("|%.*sX%.*s|\n", size/2, spaces, size/2, spaces);

for(int i=size/2+1; i<size; ++i)
{
printf("|%.*s/%.*s\\%.*s|\n", size-i-1, spaces, 2*(i-size/2)-1, spaces, size-i-1, spaces);
}
printf("+%.*s+\n", size, dashes);

return 0;
}

运行示例:

Please enter a number that will define  the size of the square: 8

Success #stdin #stdout 0s 4568KB
+-----------------+
|\ /|
| \ / |
| \ / |
| \ / |
| \ / |
| \ / |
| \ / |
| \ / |
| X |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
| / \ |
|/ \|
+-----------------+

关于c - 如何用C语言画一个不同符号和对角线的正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58941639/

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