计算数字,空格和其他字符

时间:2015-12-21 11:53:36

标签: c

#include<stdio.h>

/*Counts digits, white numbers, others*/

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=='void' || c=='\n' || c=='\t')
            ++nwhite;
        else
            ++nother;
    printf("digits= ");
    printf("%d", ndigit[i]);
    printf("whitespace=%d, other=%d\n", nwhite, nother);
}

1 个答案:

答案 0 :(得分:1)

三个变化:

  1. if(c>='0' && c<=9)if(c>='0' && c<='9')

  2. c=='void'更改为c==' '

  3. 打印每个数字的计数也应该在循环内。

    for(i=0; i<10; ++i)
        printf("%d ", ndigit[i]);
    
  4. 最终代码

    #include<stdio.h>
    
    /*Counts digits, white numbers, others*/
    
    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("\nwhitespace=%d, other=%d\n", nwhite, nother);
    }
    

    示例输出:

    [tthangavel@wtl-lview-7 test]$ ./a.out
    43n lkj1234;la sdf;akspjfoiwqe
    asdf;lkq324m n;afds
    digits= 0 1 2 3 3 0 0 0 0 0
    whitespace=6, other=37
    [tthangavel@wtl-lview-7 test]$