c 中的棋盘

Chess board in c

我想知道如何制作一个只打印棋盘上黑色位置的 c 程序,例如:
-=(空space);

-| A8 - C8 - E8 - G8 -
-| - B7 - D7 - F7 - H7
-| A6 - C6 - E6 - G6 -
-| - B5 - D5 - F5 - H5
-| A4 - C4 - E4 - G4 -
-| - B3 - D3 - F3 - H3
-| A2 - C2 - E2 - G2 -
-| - B1 - D1 - F1 - H1

#include <stdio.h>

int main()
{
    int n = 8;

    int i,j;
    char a[100][100] = {
        "A8"," ","C8"," ","E8"," ","G8",
        " ","B7"," ","D7"," ","F8"," ","H7",
        "A6"," ","C6"," ","E6"," ","G6",
        " ","B5"," ","D5"," ","F5"," ","H5",
        "A4"," ","C4"," ","E4"," ","G4",
        " ","B3"," ","D3"," ","F3"," ","H3",
        "A2"," ","C2"," ","E2"," ","G2",
        " ","B1"," ","D1"," ","F1"," ","H1",
    };
    for(i = 0;i < n;i++){
        for(j = 0;j < n;j++){
            printf("%c ",a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

绝对没有理由在这里使用二维数组。 屏幕上的表示和数据结构的内存布局不需要匹配。例如:

#include <stdio.h>

int main(void)
{
    unsigned int i;

    for (i = 0; i < 64; i++) {
        if ((((i % 8) + (i / 8)) & 1) == 0) {
            printf("%c%u ", 'A' + (i % 8), 8 - (i / 8));
        } else {
            printf("   ");
        }

        if ((i % 8) == 7) {
            printf("\n");
        }
    }

    return 0;
}

这段代码并不漂亮,但它可以工作。它甚至不使用数组。 您所需要的只是一些操作,例如除法和模数来确定行和列。然后你需要注意,如果 X+Y 是偶数,坐标为 (X,Y) 的正方形共享相同的颜色。

代码并不漂亮,但它使用了非常简单的逻辑。作为练习,在 for 循环中,尝试将坐标 X 和 Y 放入单独的变量中。那么可能更容易理解。

请阅读标有// CHANGE HERE的评论。

char a[100][100] 创建 100 个字符串,每个最大长度为 99(空终止符 1 个字符 '[=13=]'(想象 100 行 99 列)

#include <stdio.h>

int main()
{
    //int n = 8;  // CHANGE HERE - unused

    int i;

    // CHANGE HERE
    // 1. Replaced ' ' with '  ' (two spaces)
    // 2. Added '  ' after G for white H column cells
    char a[100][100] = {
        "A8","  ","C8","  ","E8","  ","G8","  ",
        "  ","B7","  ","D7","  ","F8","  ","H7",
        "A6","  ","C6","  ","E6","  ","G6","  ",
        "  ","B5","  ","D5","  ","F5","  ","H5",
        "A4","  ","C4","  ","E4","  ","G4","  ",
        "  ","B3","  ","D3","  ","F3","  ","H3",
        "A2","  ","C2","  ","E2","  ","G2","  ",
        "  ","B1","  ","D1","  ","F1","  ","H1",
    };
    
    // CHANGE HERE - chess board has 64 cells
    for (i = 0; i < 64; i++) {
        // CHANGE HERE - print a new line after every 8 entries
        if (i != 0 && i % 8 == 0)
        {
            printf("\n");
        }
        printf("%s", a[i]);
    }
    printf("\n");
    return 0;
}