【问题标题】:Printing 2d array box打印二维数组框
【发布时间】:2016-10-24 08:33:26
【问题描述】:

我是编程新手。想知道如何使用for 循环打印出盒子,让它变成一个大盒子?我附上了下面的样本。我真的需要帮助。

#include <stdio.h>

int main()
{     
 int a;

 printf("\n --- \n");
 for(a=1;a<=1;++a)
 printf("\n|   |\n");
 printf("\n --- ");

 return 0;
}

示例输出:

【问题讨论】:

  • 您向我们展示的代码有什么问题?该程序的实际输出是什么?你期望什么输出?也请read about how to ask good questions.
  • 看起来像一些家庭作业。您需要展示您所做的努力并更具体地描述您的问题。
  • @some 程序员老兄抱歉不精确,我想要打印一个二维数组框,顶部有“---”和“|”在旁边。
  • @RyanHu 供您参考,这不是家庭作业,它是我的作业计划的一部分。
  • @CristyLim 您可以编辑您的问题以使其合理。

标签: c


【解决方案1】:

这样的事情可能会奏效。您需要对嵌套循环有基本的了解才能回答这个问题。

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

int
main(int argc, char const *argv[]) {
    int rows, cols, i, j;

    printf("Enter rows for box: ");
    if (scanf("%d", &rows) != 1) {
        printf("Invalid rows\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter columns for box: ");
    if (scanf("%d", &cols) != 1) {
        printf("Invalid columns\n");
        exit(EXIT_FAILURE);
    }

    printf("\n2D Array Box:\n");
    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= cols; j++) {
            printf(" --- ");
        }
        printf("\n");
        for (j = 1; j <= cols; j++) {
            printf("|   |");
        }
        printf("\n");
    }

    /* bottom "---" row */
    for (i = 1; i <= cols; i++) {
        printf(" --- ");
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    第一个字符(' ')和重复字符串("--- ")
    第一行和重复内容行和小节行。

    #include <stdio.h>
    
    #define MARK "X O"
    
    //reduce code    
    #define DRAW_H_BAR()\
        do {\
            putchar(' ');\
            for(int i = 0; i < cols; ++i)\
                printf("%s ", h_bar);\
            puts("");\
        }while(0)
    
    void printBoard(int rows, int cols, int board[rows][cols]){
        const char *h_bar = "---";
        const char v_bar = '|';
    
        DRAW_H_BAR();//first line
        for(int j = 0; j < rows; ++j){
            //contents line
            putchar(v_bar);
            for(int i = 0; i < cols; ++i)
                printf(" %c %c", MARK[board[j][i]+1],v_bar);
            puts("");
            DRAW_H_BAR();//bar line
        }
    }
    
    int main(void){
        int board[8][8] = {
            {1,0,1,0,1,0,1,0},
            {0,1,0,1,0,1,0,1},
            {1,0,1,0,1,0,1,0},
            {0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},
            {0,-1,0,-1,0,-1,0,-1},
            {-1,0,-1,0,-1,0,-1,0},
            {0,-1,0,-1,0,-1,0,-1}
        };
        int rows = sizeof(board)/sizeof(*board);
        int cols = sizeof(*board)/sizeof(**board);
        printBoard(rows, cols, board);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 2018-12-02
      • 1970-01-01
      • 2014-03-25
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多