【发布时间】:2018-07-09 18:52:59
【问题描述】:
这是我没有使用 else if 的代码:
#include <stdio.h>
main()
{
long s = 0, t = 0, n = 0;
int c;
while ((c = getchar()) != EOF)
if (c == ' ')
++s;
if (c == '\t')
++t;
if (c == '\n')
++n;
printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}
这是使用else if的代码:
#include <stdio.h>
main()
{
long s = 0, t = 0, n = 0;
int c;
while ((c = getchar()) != EOF)
if (c == ' ')
++s;
else if (c == '\t')
++t;
else if (c == '\n')
++n;
printf("spaces: %d tabulations: %d newlines: %d", s, t, n);
}
出于某种原因,不使用 else if 不起作用。是什么原因?我知道使用 if 会一个一个地完成,而使用 else if 会在第一个正确的语句处停止。这在性能上有差异。无论如何,在这个特定(如果不是其他)while 循环中不使用 else if 似乎不起作用。
谢谢。
【问题讨论】:
-
C 不是 Python。缩进并不意味着所有这些 if 都是同一块的一部分。
-
整件事都没有
{ }。 -
第一个示例“有效”,因为第一个“if”语句仅由 while 包裹。第二个例子完全被 while 包裹起来。我会说第二个例子有效。首先没有。
-
你可能想读这个,不确定它是否是正确的重复stackoverflow.com/questions/11734604/…
-
谢谢大家。这完全表明忘记一个弯曲的括号是多么重要。这意味着我可以在没有曲括号的情况下使用“if”和“else if”,对吗? PS我是C新手,很抱歉这么愚蠢的帖子。
标签: c if-statement while-loop getchar