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
例如:如果我 将 1 传递给 n
那么:
mid_pos =1; 左空格=0; line_stars=1;
它进入循环: 左空格=-1; line_stars=3;
for 循环
打印了 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 颗星。
关于c++ - 混淆条件的评估和 for 循环的步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14034940/