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 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--);
^
|
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颗星.