【发布时间】:2014-06-18 10:04:33
【问题描述】:
我正在使用 K&R 书学习 C,并且遇到了一个显示数组使用的程序。该程序使用一个数组来记录输入的每个数字(数字)的出现,而不是存储单个数字(或者我认为)。除此之外,该程序还计算空格和其他字符。这是程序 -
#include <stdio.h>
int main(int argc, const char * argv[])
{
// insert code here...
// printf("Hello, World!\n");
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("\n white space= %d, other=%d\n", nwhite,nother);
return 0;
}
这是一个示例输出-
my birthday was 08081980
hello
digits = 3100000031
white space= 5, other=18
我花了一段时间才弄清楚ndigit 数组记录了每个数字出现的次数。示例-0 在我的输入中出现 3 次。
但是,我无法弄清楚数组是如何通过循环设置的。一开始,
for(i=0;i<10;i++)
ndigit[i]=0;
这个 for 循环将 ndigit 数组的每个元素设置为零。但是后来,我不明白这个 if 语句会发生什么-
if (c>='0' && c<='9') {
++ndigit[c-'0'];
}
这可能是因为我以前没有遇到过这种类型的代码。 ++ndigit[c-'0'] 表达式试图做什么?这是否假设输入的每个数字都是字符的形式,然后通过其 ASCII 值在内部转换为 int? c -'0' 表达式在这里做什么?
非常感谢您在这方面的帮助。
【问题讨论】: