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

MTV*_*TVS 0 c c++ for-loop step-into

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);
}
Run Code Online (Sandbox Code Playgroud)

...

我有问题就在这里,当我step intofor 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.

我很困惑,如果有人能提供帮助,我会很感激.

Jos*_*eld 5

哦,哦,注意偷偷摸摸的分号:

for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
                                                                            ^
                                                                            |
Run Code Online (Sandbox Code Playgroud)

这结束了你的for陈述.循环将一直运行直到line_stars大于n.到最后,line_stars现在将等于3(因为它增加了2).left_spaces将是-1.

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

  • 小建议:`for(line_stars,left_spaces;` - 除了占用行上的空间,这绝对没有.使用`for(; ...`如果你没有什么可以初始化就行了. (3认同)