如何仅在使用while循环(无阵列)的情况下在C框中打印框 [英] How do I print boxes inside of boxes in C whilst only using while loops (without arrays)
问题描述
只需要使用while循环和if语句来解决这个问题所需的正确逻辑需要一些直觉
我需要能够按照这样的标题中所述打印盒子内的盒子。
我尝试过:
Need some intuition on the correct logic needed to solve this problem with only using while loops and if statements
I need to be able to print boxes inside of boxes as stated in the title like this.
What I have tried:
#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;
int row = 0;
while (row < boxSide) {
int column = 0;
while (column < boxSide) {
if ((row % 2 == 0) && (column % 2 ==0)) {
printf("#");
}
else if (row == 0 || row == boxSide-1 || column == 0 || column == boxSide-1) {
printf("#");
}
else if ((column == boxSide/2) && (row % 2 == 0)) {
printf("#");
}
else if ((row == boxSide/2) && (column % 2 == 0)) {
printf("#");
}
else {
printf(" ");
}
column++;
}
row++;
printf("\n");
}
return 0;
}
推荐答案
停下来想一想:自己画框并看看它们是如何构建的。
Stop and think about it: draw the boxes yourself and look at how they are constructed.
##### 11111
##### 12221
## ## 12 21
##### 12221
##### 11111
是两个盒子
Is two boxes
####### 1111111
####### 1222221
####### 1233321
### ### 123 321
####### 1233321
####### 1222221
####### 1111111
三个盒子
到目前为止有道理吗?
所以你需要两个while循环:外部循环覆盖行,需要运行 2n + 1
次,其中 n
是框。 (因为你有2个一半要绘制,一个中间行。)
内部一个覆盖列,并且还运行 2n + 1
时间也是出于同样的原因。
在两个循环中,除非你在中心,否则打印#。如果你在中心,打印。
如果你想的话很容易......但这是你的功课,所以我不编码for yoU!
Is three boxes
Make sense so far?
So you need two while loops: the outer one covers rows, and needs to run 2n + 1
times, where n
is the number of boxes. (Because you have 2 "halves" to draw, and a single middle row.)
The inner one covers columns, and also runs 2n + 1
times for the same reason.
In side both loops, unless you are right at the centre, print "#". If you are at the centre, print " ".
Pretty easy if you think about it ... but this is your homework, so I'm not coding it for yoU!
使用光线投射。
您可以计算每个框的坐标和边界。 br />
然后你遍历每个单元格(每个col,逐行),看看它击中哪个框;如果原始的盒子计算是正确的,它只能击中一个而且只有一个。
(第一行单元格将全部击中外边界框;然后是最外面的2;下一个内盒顶部等等。)
颜色命中了带有该框字符的单元格。
Use "ray casting".
You can calculate the coordinates and "boundaries" of each box.
You then iterate over each "cell" (each col, by row) and see which box it "hits"; it can only hit one and only one if the original "box calculations" are correct.
(The first row of cells will all "hit" the outer bounding box; then the outer most 2; with the next inner box top hit, etc.)
"Color" hit cells with a character for that box.
考虑一下:
Consider this:
####### 3333333
# # 3 3
# ### # 3 111 3
# # # # 3 1 1 3
# ### # 3 111 3
# # 3 3
####### 3333333
你知道一个位置是否是一个盒子边框,取决于到盒子中心的距离。
You know if a position is a box border or not depending on the distance to center of boxes.
这篇关于如何仅在使用while循环(无阵列)的情况下在C框中打印框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!