#include<stdio.h>
/*countdigits,whitespace,others*/
main()
{
intc,i,nwhite,nother;
intndigit[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']; //THIS IS THE LINE I AM WONDERING ABOUT
else if(c==''||c=='\n'||c=='\t')
++nwhite;
else
++nother;
printf("digits=");
for(i=0;i<10;++i)
printf("%d",ndigit[i]);
printf(",whitespace=%d,other=%d\n",
nwhite,nother);
}
该程序自身运行的输出是
digits=9300000001,whitespace=123,other=345
声明
intndigit[10];
将 ndigit 声明为包含 10 个整数的数组。在 C 中数组下标始终从零开始,因此元素是
ndigit[0], ndigit[ 1], ..., ndigit[9]
这反映在初始化和打印数组的 for 循环中。下标可以是任何整数表达式,其中包括像 i 这样的整数变量和整数常量。这个特定的程序依赖于数字的字符表示的属性。例如,测试
if(c>='0'&&c<='9')
判断c中的字符是否为数字。如果是,则该数字的数值为
c-'0'`
仅当“0”、“1”、...、“9”具有连续递增值时才有效。幸运的是,这对于所有字符集都是如此。根据定义,字符只是小整数,因此字符变量和常量与算术表达式中的整数相同。这是自然而方便的;例如
c-'0'
是一个整数表达式,其值在 0 到 9 之间,对应于存储在 c 中的字符“0”到“9”,因此是数组 ndigit 的有效下标。