【问题标题】:Incrementing and printing variable in the same for loop在同一个for循环中递增和打印变量
【发布时间】:2018-12-28 15:43:48
【问题描述】:

我正在尝试在 for 循环中增加变量 x 并在每次迭代时打印它。

include <stdio.h>

int x = 0;

void main()
{    
    int c;
    for (c = 1; c <= 5; c++)

        x++;
        printf("%d", x);

}

我想要的输出是:

12345

但是这段代码只打印出来:

5

当我不增加 x 时,我可以在每次迭代时打印:

# include <stdio.h>

int x = 0;

void main()
{    
    int c;
    for (c = 1; c <= 5; c++)

        //x++;
        printf("%d", x);

}

输出:

00000

为什么在循环中增加 x 会改变 printf 的行为?

【问题讨论】:

  • 您的代码块周围缺少花括号。
  • 您可能有 Python 背景。 :)

标签: c scope printf


【解决方案1】:

问题是,您在这里缺少 块范围

声明

for (c = 1; c <= 5; c++)

    x++;
    printf("%d", x);

相同
for (c = 1; c <= 5; c++)
{
    x++;
}
printf("%d", x);

所以,您的打印语句不是循环的一部分。

另一方面,当您注释x++; 语句时,printf() 语句被视为循环体。

您需要使用大括号来强制执行该块,例如

for (c = 1; c <= 5; c++)
{
    x++;
    printf("%d", x);
}

【讨论】:

    【解决方案2】:

    for 循环的主体只包含一个命令,即x++;。请注意,编译器不关心缩进,只关心花括号。

    写...

    for (c = 1; c <= 5; c++) {
        x++;
        printf("%d", x);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-15
      • 2020-02-10
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2020-04-21
      相关资源
      最近更新 更多