xcode 如何在C中制作棋盘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40252555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:29:53  来源:igfitidea点击:

How to make a chessboard in C?

c++cxcodechess

提问by Shamveel Ahammed

I am new to C and I am trying to make a program that would output a chessboard pattern. But, I don't understand what my next steps are going to be . Could anyone help me with this?

我是 C 的新手,我正在尝试制作一个可以输出棋盘图案的程序。但是,我不明白我的下一步将是什么。有人可以帮我解决这个问题吗?

Main:

主要的:

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

int main() {
    int length,width;
    enum colors{Black,White};

    printf("Enter the length:\n");
    scanf("%d",length);
    printf("Enter the width:\n");
    scanf("%d",width);

    int board[length][width];
    createBoard(length,width);
    for(int i =0;i< sizeof(board);i++) {

        if(i%2==0) {
            // To print black
            printf("[X]");
        }
        else {
            // To print white
            printf("[ ]");
        }
    }
} //main

CreateBoard function:

创建板功能:

int createBoard(int len, int wid){
    bool b = false;
    for (int i = 0; i < len; i++ ) {
        for (int j = 0; j < wid; j++ ) {
            // To alternate between black and white
            if(b = false) {
                board[i][j] = board[White][Black];
                b = false;
            }
            else {
                board[i][j] = board[Black][White];
                b = true;
            }
        }
    }
    return board;
}

回答by Ishpreet

Firstly learn how to use scanf().

首先学习如何使用scanf()。

int length;

Incorrect: scanf("%d",length); Correct: scanf("%d",&length);

不正确: scanf("%d",length); 正确: scanf("%d",&length);

Hope this helps:

希望这可以帮助:

#include <stdio.h>

int main(void) 
{
    int length,width,i,j;
    printf("Enter the length:\n");
    scanf("%d",&length);
    printf("Enter the width:\n");
    scanf("%d",&width);
    for(i=1;i<=length;i++)
    {
        for(j=1;j<=width;j++)
        {
            if((i+j)%2==0)
                printf("[X]");
            else printf("[ ]");
        }
        printf("\n");
    }
    return 0;
}

Note: Make sure length and width are of even length.

注意:确保长度和宽度的长度相等。