繁体   English   中英

与条件评估和for循环步骤混淆

[英]confusion with evaluation of the condition and the steps of a for loop

void draw_diamond(int n)
{
int mid_pos = ceil((double)n / 2);
int left_spaces = mid_pos-1;
int line_stars = 1;

putchar(10);
//printing from top through the middle of the diamond
for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
{
    //printing the left_spaces
    for(int i=1; i<=left_spaces; i++)
        putchar(32);

    //printing the line_stars
    for(int i=1; i<=line_stars; i++)
        putchar('*');
    putchar(10);
}

...

我在这里遇到问题,当我step into for loop时,什么也没发生,因为第二个for loop step is applied例如:如果我pass 1 to n则:

mid_pos = 1; left_spaces = 0; line_stars = 1;

它进入循环:left_spaces = -1; line_stars = 3;

for loop打印3个星号,该区域应仅打印1个星号。

我很困惑,如果有人可以帮忙,我将不胜感激。

哦,小心那些偷偷摸摸的分号:

for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
                                                                            ^
                                                                            |

这样就结束了您的for语句。 循环将一直运行,直到line_stars大于n为止。 到最后, line_stars现在将等于3(因为它增加了2)。 left_spaces将为-1。

现在将执行大括号括起来的其余代码。 第一个for循环根本不会运行,但是第二个循环将从1开始运行,直到line_stars并且正如我们所知, line_stars为3,所以我们打印了3个星星。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM