计算整数中数字的出现次数

时间:2012-10-19 20:49:08

标签: c function

我想计算某个数字出现在一个整数内的频率。我有以下代码:

int main()
{
    printf ("Put numbers\n");

    int cislo;
    int s0,s1,s2,s3,s4,s5,s6,s7,s8,s9;

    while(scanf("%d",&cislo)==1){
        if (cislo<0)
            printf ("Cislo %d, je zaporne, takove neberu", cislo);
        continue;
    }

    s0=s1=s2=s3=s4=s5=s6=s7=s8=s9=0;
    do{
        (cislo/=10);
        switch (cislo%10){
            case 0: ++s0; break;
            case 1: ++s1; break;
            case 2: ++s2; break;
            case 3: ++s3; break;
            case 4: ++s4; break;
            case 5: ++s5; break;
            case 6: ++s6; break;
            case 7: ++s7; break;
            case 8: ++s8; break;
            case 9: ++s9; break;
        }
    }while (cislo>0);

    printf ("Zadane cislo se sklada z cislic: \n\n 0 ... %dx \n 1 ... %dx \n 2 ... %dx \n 3 ... %dx \n 4 ... %dx \n 5 ... %dx \n 6 ... %dx \n 7 ... %dx \n 8 ... %dx \n 9 ... %dx \n",s0,s1,s2,s3,s4,s5,s6,s7,s8,s9);

    return 0;
}

它必须如何运作:

Put number:
1111111111

Number: 1111111111 

include:
0 ...  0x
1 ... 10x
2 ...  0x
3 ...  0x
4 ...  0x
5 ...  0x
6 ...  0x
7 ...  0x
8 ...  0x
9 ...  0x

它是如何运作的:

Put number: 
1111111111

Number: 1111111111 

include:
0 ...  1x
1 ...  9x
2 ...  0x
3 ...  0x
4 ...  0x
5 ...  0x
6 ...  0x
7 ...  0x
8 ...  0x
9 ...  0x

有谁知道为什么?

2 个答案:

答案 0 :(得分:2)

mod后的数字:

 do{
    switch (cislo%10){
    case 0: ++s0; break;
    case 1: ++s1; break;
    case 2: ++s2; break;
    case 3: ++s3; break;
    case 4: ++s4; break;
    case 5: ++s5; break;
    case 6: ++s6; break;
    case 7: ++s7; break;
    case 8: ++s8; break;
    case 9: ++s9; break;
    }
    cislo/=10;
 }while (cislo>0);

因此,您在计算时缺少一位数字。

您的输入法不是很好。因为,您只想接收一个整数:

while(scanf("%d",&cislo)!=1){

更合适。

您也可以使用数组s[10]而不是10个整数。

答案 1 :(得分:0)

更改do / while循环:

do {
    int nextval = cislo / 10;

    switch (cislo - (nextval*10)) {
        case 0: ++s0; break;
        case 1: ++s1; break;
        case 2: ++s2; break;
        case 3: ++s3; break;
        case 4: ++s4; break;
        case 5: ++s5; break;
        case 6: ++s6; break;
        case 7: ++s7; break;
        case 8: ++s8; break;
        case 9: ++s9; break;
    }

    cislo = nextval;
} while (cislo>0);