[英]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.