【发布时间】:2013-06-30 15:41:26
【问题描述】:
只是一个简单的问题;我一直在研究 K&R,数字/空格/其他计数器的代码工作正常。但是,在尝试了解 else 的功能时,我遇到了一些无法按预期工作的问题。
书中的代码如下:
#include <stdio.h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
如果我随后修改 while 循环,使其显示为:
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
它应该仍然具有与原始代码相同的功能,只是它不会计算“其他”字符。然而,我实际上得到的实际上只是“数字”部分工作,无论输入是什么,“nwhite”都返回零。我觉得这种差异可能是由于对 if 语句的功能存在根本性的误解。
【问题讨论】:
-
你需要大括号。
-
请注意,许多人总是使用大括号编写
while (expression) { statement; ... },以避免出现此错误。
标签: c if-statement