田安Anne

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
貌似没什么难的
不想解释了
算了,疏通下逻辑把
定义整形变量 c , i , nwhite,nother
再定义长度位10的整型数组ndigit[10]
那个for是将数组的值都初始化为0了
下面是循环体的执行,条件依旧是那个,已经讲过
那个
if (c >= '0' && c <= '9')
    ++ndigit[c - '0'];
可以自己单独执行,会发现这里是,如果你输入的是9,那么第ndigit[9]个就+1,以此类推
到了else if那里,执行从左到右,只要有一个为真,立马执行,比如你输入9,那么nwhite会+1
因为getchar()吸收了一个\n,如若你输入的是‘9 ’,nwhite = 2,它的执行流程就是9循环一次,空格循环一次,'\n'再循环一次
最后将数组打印出来,这又是有点类似于标志寄存器的思想了
int 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);
        system("pause");
        return 0;
}
 
posted on 2018-08-07 09:44  田安Anne  阅读(989)  评论(0编辑  收藏  举报