丙 |仅使用 for/while 循环和 if/else 语句打印 Boxes inside Boxes

标签 c loops for-loop if-statement

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

这是我需要的:

enter image description here

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

#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;
}

enter image description here

最佳答案

NCurses 是您的 friend 。

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

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

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

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

关于丙 |仅使用 for/while 循环和 if/else 语句打印 Boxes inside Boxes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699739/

相关文章:

c - 在c中打印更新变量

c - 在C程序中使用sed时出现"unknown escape sequence"警告

javascript - For循环跳过重复值

c - Valgrind - 复制/释放数组时内存泄漏

Java蛇眼程序错误

optimization - 继续循环 if 语句内 vs. 在循环内使用 if 语句的否定

Python for 循环声明和行为

c - 如何在 C 中将 double 组转换为整数数组?

R for 循环 n 次

c# - 有没有用 C# 将 Java 库编译成可包装的东西的例子?