0
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 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 颗星。

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

4

1 回答 1

5

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

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

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

Now the rest of your code which is enclosed by curly brackets will execute. The first for loop won't run at all, but the second one will run from 1 until line_stars and, as we know, line_stars is 3, so we get 3 stars printed out.

于 2012-12-26T00:31:53.637 回答