首页 > 解决方案 > 如何用不同的符号和对角线在C中绘制一个正方形?

问题描述

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

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

我已经尝试学习和研究了 3 个小时,观看了 20 个不同的 YouTube 视频并阅读了 20 个不同的编码指南。太令人沮丧了。。

谢谢。

我附上了我的代码和输出的图片,以及右侧的所需输出。在此处输入图像描述

代码本身:

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");
        }

标签: cvisual-studio

解决方案


#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        |
    |       / \       |
    |      /   \      |
    |     /     \     |
    |    /       \    |
    |   /         \   |
    |  /           \  |
    | /             \ |
    |/               \|
    +-----------------+

推荐阅读