出现不需要的换行符

Unwanted newline appearing

每当我 运行 我的程序时,它直到换行后才开始打印星号,为什么? 这是我的代码:

int main()
{
    int createRow = 0,
        createCol;

    while (createRow <= 5)
    {
        while (createCol <= ((createRow * 2) - 1))
        {
            printf("*");
            createCol++;
        }
        createCol = 1;
        createRow++;

        printf("\n");
    }
    return 0;
}

输出:

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

如您所见,就在第一个星号之前,有一个换行符。我该如何解决这个问题?

createCol 未初始化并在赋值前使用。

进行以下更改

int createRow = 1,
    createCol = 0;  

while (createRow <= 5)
{
    while (createCol <= ((createRow * 2)-1))
    {
       //Loop body
    }
    createCol = 0;
    // Rest of the code
}

您可以通过更改

将其删除
printf("\n");

createRow == 1 ?: printf("\n");

这与下面的相同,但更简洁并且对于知道如何使用 ternary operator.

的程序员来说更有意义
if (createRow != 1) {
   printf("\n");
}

当使用三元运算符 condition ? expression1 : expression2; 时,不需要 expression1expression2 是必需的。 Expression1 条件为真时执行,expression2 条件为假时执行。