简明现代魔法 -> C/C++ -> C 程序设计:使用数组
C 程序设计:使用数组
2010-02-19
问题:编写一个程序,以统计各个数字、空白符(包括空格符、制表符及换行符)、以及所有其它字符出现的次数。
所有的输入字符可以分为12类,因此可以用一个数组存放各个数字出现的次数,这样比使用10个独立的变量更方便。
#include <stdio.h>
/* 统计各个数字、空白符及其它字符出现的次数 */
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);
}
下列语句判断 c 中的字符是否为数字。
if(c >= '0' && c <= '9')
如果它是数字,那么该数字对应的数值是 c - '0'。
