【发布时间】:2022-01-25 05:30:30
【问题描述】:
完全披露:我想我已经通过形式化所有这些来回答我自己的问题。请问你能检查我的逻辑吗?
使用以下术语: for (初始化控制变量;循环继续条件[布尔表达式];de/increment)
我写了一个循环,打印出一个马里奥风格的金字塔:
Welcome to Super Mega Mario!
Height: 5
# #
## ##
### ###
#### ####
##### #####
在代码中,我使用了两种不同的循环继续条件:
for (int z = i + 1; z > 0 ; z--)
for (int z = i + 1; z ; z--)
我不确定为什么第二个例子有效,下面是我的解释。
为什么我认为这两种方法都有效:
第一个例子(z > 0):
要打印最后一行##### #####,for 函数会打印“#”5 次。首先,因为z == 5,所以Bool为真,所以打印“#”。那么 z == 4,Bool 为真,所以打印“#”。这继续 直到 z == 0,所以 Bool 为 FALSE,因此中断。
第二个例子(z):
所有非零值都为真,z 为 5,4,3,2,1。当 z 为 0 (FALSE) 时,中断。
我正在学习,我想开发优秀的风格和设计,如果你能解释哪个例子设计得更好,请告诉我!另外,如果你可以推荐我的风格的编辑,那么也请 HMU。 【源码@end】。
int main(void)
{
int n;//Declare variables outside of loops to allow "while" function to use it.
printf("Welcome to Super Mega Mario! \n");
do
{
n = get_int("Height: "); //prompt user for height of pyramid.
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++)//How many rows will be created
{
for (int j = 0; j < n; j++) //column
{
for (int x = n - i - 1; x; x--) //for(initialise control variable; loop continuation condition [boolean expression]; increment)
{
printf(" ");
}
for (int y = i + 1; y; y--) //If the loop continuation condition is y, then it's TRUE. So the function will run. Then it decreases this value by 1, so it's now 0 or FALSE so the function breaks.
{
printf("#");
}
printf(" ");
for (int z = i + 1; z > 0 ; z--) //In theory "z>0" works the same as z on its own.
{
printf("#");
}
break;
}
printf("\n");
}
}
【问题讨论】:
-
在一个条件下,
if (z)与if (z != 0)相同。也适用于 for 循环条件。