【问题标题】:confusion with evaluation of the condition and the steps of a for loop与条件评估和 for 循环的步骤混淆
【发布时间】:2012-12-26 00:27:48
【问题描述】:
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 在应该只打印 1 的地方打印 3 颗星。

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

【问题讨论】:

    标签: c++ c for-loop step-into


    【解决方案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 颗星。

    【讨论】:

    • 次要建议:for(line_stars, left_spaces ; - 除了占用在线空间之外,这绝对没有任何作用。如果您没有任何需要初始化的内容,请使用for(;...
    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 2018-09-08
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多