为什么我的for循环打印不像我期望的伪代码?

Cal*_*Jay 7 c

int main(void)
{
int height = 24;

while (height > 23 || height <=0)
{
printf("How tall do you want the tower to be?\n");
height = GetInt();
}

for(int a = 0; a < height; a++)
{
    for(int c = a; c<=height; c++)
    {
        printf(" ");
    }
    for(int b = height - a; b<=height; b++)
    {
        printf("#");
    }
    printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)

所以,我要做的是有一个塔与终端窗口的左边缘对齐.但是出于某种原因,这会在"最后一行"(塔底)的开头产生两个额外的空格.甚至更奇怪的是,当我用笔和纸坐下并手动完成程序时,我显示第一行应该有一些空格,等于"高度"+ 1,后面跟着一个"#"然后是一个新行,然后是一个等于"height"的空格,后跟两个"#",依此类推.为什么我的代码不是那样评估的,而且我的两个额外空格是什么?对不起的解释很抱歉.

P.P*_*.P. 4

这是因为您height + 1在每行的开头打印,而您想打印height-1空格。

更改您的条件:

for(int c = a; c<=height; c++)
Run Code Online (Sandbox Code Playgroud)

for(int c = a; c<height-1; c++)
Run Code Online (Sandbox Code Playgroud)

  • 它不仅仅特定于最后一行。很容易看出问题是输入1作为高度。 (2认同)