UVa 1225“数字计数”的C“运行时错误”

时间:2018-07-24 09:45:52

标签: c runtime-error uva

我正在解决UVa问题。在UVa中检查时,它显示“哇!您的输出与接受的输出相同!”。但是,当我提交代码时,它一直显示“运行时错误”。我不知道为什么会这样,或者为什么“根本会发生运行时错误”。

这是问题所在-> https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=16&page=show_problem&problem=3666

这是我的代码->

#include <stdio.h>
#include <stdlib.h>

int main()
{
int j=0,n,num,i,a[10000],b[10],k,it,l;
scanf("%d",&it);
for(l=0; l<it; l++)
{

    scanf("%d",&n);
    j=0;
    for(i=1; i<=n; i++)
    {
        num=i;
        while(num!=0)
        {
            k=num%10;
            num=num/10;
            a[j]=k;
            j++;
        }
    }
    a[j]=9999;

    for(i=0; i<=9; i++)
    {
        b[i]=0;
    }

    for(j=0; a[j]!=9999; j++)
    {
        b[a[j]]++;
    }

        printf("%d",b[0]);

    for(i=1; i<=9; i++)
    {
        printf(" %d",b[i]);
    }
    printf("\n");
}
return 0;
}

1 个答案:

答案 0 :(得分:0)

The RunTime Error occurring in you code is segmentation fault . This is because of you usage of a[10000]. In your code a[j]=k; you are using so much of memory.(for a 2 digit number you use 2 array locations , 3 digit 3 etc) So for a number greater than 3000 (approx) You is go out of limit 10000 and results a segmentation error.

You don't need that a[10000] to implement the counting code.

Try this simplified code :-

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, num, i, b[10], k, it, l;
    scanf("%d", &it);
    for (l = 0; l < it; l++)
    {
        for (i = 0; i <= 9; i++)
        {
            b[i] = 0;
        }

        scanf("%d", &n);
        for (i = 1; i <= n; i++)
        {
            num = i;
            while (num != 0)
            {
                k = num % 10;
                num = num / 10;
                b[k]++;
            }
        }
        printf("%d", b[0]);

        for (i = 1; i <= 9; i++)
        {
            printf(" %d", b[i]);
        }
        printf("\n");
    }
    return 0;
}

Output :-

2
3
13
0 1 1 1 0 0 0 0 0 0
1 6 2 2 1 1 1 1 1 1