【问题标题】:How to increment a counter for a while loop within the loop? [duplicate]如何为循环内的while循环增加计数器? [复制]
【发布时间】:2017-06-19 02:40:15
【问题描述】:

我有一种感觉,我在这里会感到非常愚蠢,但我只是在学习使用 ++-- 来增加和减少 while 循环的变量,并且想知道为什么这段代码有效并且为什么没有?

错误代码:

int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

错误代码无限期地输出零。

工作代码:

int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

这个想法是输出为 012345678910,但即使在工作代码中,它也是从 1 开始到 10,而不是从 0 开始。即使 ctr 的初始值为 0。

【问题讨论】:

  • C 不关心你的空格和手动缩进。你需要一些{}
  • C 不是 Python。缩进在 C 中无关紧要——至少对编译器来说不重要,但试图阅读代码的人会关心它。
  • 只是补充一下@JonathanLeffler 所说的,编译器无论如何都会读取和翻译你的代码,只是人类会放弃你的代码。
  • 您的错误代码缺少花括号:int ctr = 0; while (ctr

标签: c while-loop post-increment postfix-operator


【解决方案1】:
int ctr = 0;
while (ctr++ <= 10)
{ 
    printf("%d",ctr-1);
}

输出为012345678910

【讨论】:

  • 输出?您在这段代码中的什么地方打印?
  • var test 无效 C. 你没有打印任何东西?
  • 编辑后的代码至少是 C。但是,在打印中使用ctr - 1 是一种常规(且不必要)。您可以在对printf() 的调用中应用++——如printf("%d", ctr++);——并从while 条件中省略它。输出包含请求的前导零 - 但示例输出最初不包含该零。关于 SO 的好的答案往往会更多地解释为什么修复是合适的以及为什么原来的被破坏了。
【解决方案2】:

第一种情况

while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

while 循环体被视为printf() 语句。 ctr=ctr+1; 不是循环体的一部分。所以你在循环条件检查中有一个不变的变量,这使它成为无限循环。

您需要使用{} 将这两个语句括在一个块范围内,以便两个语句都成为循环体的一部分。类似的东西

while (ctr < 10) {
  printf("%d",ctr);
  ctr=ctr+1;
}

会的。


第二种情况

int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

ctr 已经在 while 条件检查表达式中作为后缀递增运算符的副作用而递增。因此,在打印值时,会打印已经增加的值。

【讨论】:

  • @KeineLust 对,谢谢指出
【解决方案3】:

确实很简单。

int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
  ctr=ctr+1;

在这第一段代码中,尽管有缩进,但你的while 只涉及printf("%d",ctr);,因为没有阻止ctr=ctr+1; 属于while

可以这样写:

int ctr = 0;
while (ctr < 10)
  printf("%d",ctr);
ctr=ctr+1;     // This is not in the loop, even with the previous indentation.

在这个循环中ctr 没有增量,然后它将永远运行并打印零。

在第二段代码中

int ctr=0;
while (ctr++ < 10)
    printf("%d",ctr);

您每次通过都会增加ctr,它会正常工作。

如果你想让第一个循环工作,这样写:

int ctr = 0;
while (ctr < 10) {
  printf("%d",ctr);
  ctr=ctr+1;
}

现在ctr=ctr+1; 确实在while 循环内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    相关资源
    最近更新 更多