只是一个简单的问题; 我一直在通过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);
}
Run Code Online (Sandbox Code Playgroud)
如果我然后修改while循环所以它读取:
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
Run Code Online (Sandbox Code Playgroud)
它应该仍然具有与原始代码相同的功能,除了它不会计算"其他"字符的事实.然而我实际得到的实际上只是'数字'部分工作,无论输入是什么,'nwhite'都返回零.我觉得这种差异可能是由于对if陈述如何发挥作用的根本误解.
oua*_*uah 10
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
Run Code Online (Sandbox Code Playgroud)
第二个if语句不再处于循环中.使用{和}包含循环语句.
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |