在 C 中打印带有星号的金字塔图案时出错

Error printing a pyramid pattern with asterisks in C

程序要求用户输入金字塔高度,即:行数,并打印出金字塔。

输入 5,结果应如下所示:

    *
   ***
  *****
 *******
*********

我写的代码是:

#include <stdio.h>

void main()

{
    int i, j, n = 0;

    printf("enter pyramid hight: \t");
    scanf("%d", &n);

    // FOR EACH ROW:
    for (i = 0; i < n; i++)
    {
        // print spaces till middle:
        for (j = 0; j < (n - 1 - i); j++)
        {
            printf(" ");
        }

        // print stars:
        for (j = 0; j < 2 * n + 1; j++)
            ;
        {


            printf("*");

            // go to new row
            printf("\n");
        }
    }
}

但结果是:

    *
   *
  *
 *
*

究竟是哪里出了问题,我认为第二个循环可能是问题所在,但我无法确定原因。

第二个 for 循环出现逻辑错误,它没有按照您的要求执行:

    // print stars:
    for (j = 0; j < 2 * n + 1; j++)  //<-- error #1 - n should be i as it's specific for this row
        ;  //<-- error #2 - this termination is completely wrong, it means this `for` loop doing nothing
    {


        printf("*");

        // go to new row
        printf("\n");
    }

应该是:

    // print stars:
    for (j = 0; j < 2 * i + 1; j++)
    {
        printf("*");
    }
    // go to new row
    printf("\n");