【问题标题】:C | Print Boxes inside of Boxes with only for/while loops and if/else statementsC |仅使用 for/while 循环和 if/else 语句在 Box 内打印 Box
【发布时间】:2018-08-06 02:05:20
【问题描述】:

我的代码有一个错误,即在不同的行上而不是在彼此的内部打印这些框。我假设问题出在我最初的 for 循环上;我不确定如何调整算法。 任何帮助将不胜感激!

这是我需要的:

这是我目前拥有的代码及其输出:

#include <stdio.h>

int main(void) {

    int boxes;

    printf("How many boxes: ");
    scanf("%d", &boxes);


    int boxSide = boxes *3 + (boxes - 1);
    int i;
    int j;

    for (i = 0, j = 0; i < boxes; i++, j += 2) { 

        int row = 1;   

            while (row <= boxSide) {

                int column = 1;

                while (column <= boxSide) {

                    if ( (row == (j+1) && column >= (j+1) && column <= boxSide - (j+1)) ||
                         (row == boxSide - j && column >= (j+1) && column <= boxSide - (j+1)) ||
                         (column == (j+1) && row >= (j+1) && row <= boxSide - (j+1)) ||
                         (column == boxSide - j && row >= (j+1) && row <= boxSide - j) ) {

                    printf("#");

                    }

                    else {
                        printf(" ");
                    }

                column++;

                }

                row++;
                printf("\n");

            }

    }
    return 0;
}

【问题讨论】:

  • 这个问题在哪里被问及没有得到适当的回答?
  • 你需要重新考虑你的逻辑,当你达到它的线等时,你需要重新考虑你的逻辑并从内盒开始,而不是像你现在做的那样写 3 个单独的盒子

标签: c loops for-loop if-statement


【解决方案1】:

NCurses 是你的朋友。

它有在指定位置打印东西的方法。

Here 是一个解释所有方法、什么是 NCurses 以及如何使用它的教程。

但是,要回答您的问题...

发生这种情况是因为,除非您使用像 NCurses 这样具有将光标移动到任意位置的方法的库,否则println()(或printf("\n"))会将光标移动到下一个可用行。

【讨论】:

    【解决方案2】:

    有几种方法可以做到,一些想法:

    1) 绘制到一个数组,绘制完成后,打印它的内容:

    char table[boxSide][boxSide]; 
    ...
    if (...) {
        table[x][y] = '#';
    }
    ...
    

    2) 将盒子循环移动到最内层循环:

    while (row <= boxSide) {
        while (column <= boxSide) {
            char c = ' ';
            for (i = 0, j = 0; i < boxes; i++, j += 2) {                        
                if ( .... ) {
                    c = '#';
                }
            }
            printf('%c', c); 
            ...
    

    【讨论】: