【问题标题】:Unwanted newline appearing出现不需要的换行符
【发布时间】:2015-04-23 09:16:11
【问题描述】:

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

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

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

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

输出:

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

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

【问题讨论】:

  • 嗯,换行符没有出现在这里,但在第一个星号之前有一个
  • 问:你忘记初始化createCol了吗?
  • 将printf("\n");更改为createRow==1 ?: printf("\n");

标签: c loops random newline


【解决方案1】:

你可以通过改变来移除它

printf("\n");

到

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

这与以下相同,但更简洁,对知道如何使用ternary operator的程序员来说更有意义。

if (createRow != 1) {
   printf("\n");
}

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

【讨论】:

  • @Jongware ... 误用三元运算符?我认为三元运算符的这种用法并不深奥,而且它比 if 语句更简洁。
  • 只要他了解三元运算符是什么以及它是如何工作的,最好让他接触到使用它的好例子(像这样短的一个衬里)而不是链式表达式。 @Jongware
【解决方案2】:

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

进行以下更改

int createRow = 1,
    createCol = 0;  

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    相关资源
    最近更新 更多