簡體   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