我正在阅读 C 编程语言第 2 版。我正在教程介绍中做 2.10。我必须编写一个关于数组的程序。它应该计算数字、空格等。这是程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
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 = %dn", nwhite, nother);
return 0;
}
根据这本书,程序本身的输出是
数字 = 9 3 0 0 0 0 0 0 00 1,空格 = 123,其他 = 345
我有两个问题:
- 如果不执行 CTRL+Z,程序将如何自行输出?
- 当我手动执行此操作时,输出不正确。请查看我在代码中是否犯了错误。
我得到的输出是
数字 =,空格 = 0,其他 = 0
这个:
printf("digits =");
for (i = 0; i < 0; ++i)
printf(" %d ", ndigit[i]);
for
循环的标头中有一个损坏的中间部分; i < 0
不会是真的(永远!),所以循环不会运行。
for (i = 0; i < 0; ++i)
这是错误的。