为什么我从函数调用中获取垃圾值?

时间:2014-11-29 06:32:52

标签: c return-value garbage

我根据this link使用C中的memoization进行递归,在spoj上做问题FARIDA。在下面的代码中,我在调用函数solve时得到变量t2的垃圾值。我在控制台上粘贴了打印值t2的图像。检查3-4次后,我无法找到导致该行为的原因。请帮我解决一下这个。感谢。

#include<stdio.h>

long int a[1000];
long int cache[1000];
int n;


long int max(long int a,long int b)
{
    if(a>b)
        return a;
    else
    return b;
}


long int solve(int i)
{
    //printf("%d\n",i);
    long int t1,t2,t;
    if(i>(n-1)){
            printf("i=====%d n=====%d\n",i,n);
        return 0;
    }
     if(cache[i]!=-1)
        return cache[i];

    t1=solve(i+2); // i+2 because we cant get a coin from the monster i+1.
    t2=solve(i+3); 
    printf("t1::: %lld t2::: %lld\n", t1, t2);
    t = max(t1,t2)+a[i];
    cache[i] = t;
    printf("i::: %d t::: %lld\n", i, t);
    return t;
}

int main()
{
    int t,i;
    long int answer;
    scanf("%d",&t);// no. of test case
    while(t--)
    {
        scanf(" %d", &n); //no. of monsters.

       for(i=0;i<n;i++)
       {
            a[i] = 0;
            cache[i] = -1;
            scanf(" %lld", &a[i]);//no. of coins each monster can give
        }
        answer = solve(0);
        printf("%lld\n",answer);
    }
}

这是控制台上的输出,显示打印的位置t = 10和n = 8

10
8
218 8 15 22 29 115 2100 2000
i=====8 n=====8
i=====9 n=====8
t1::: 0 t2::: 11008688374415360  // here t2 should be equal to 0 but thats not the case
i::: 6 t::: 2100
i=====9 n=====8
i=====10 n=====8
t1::: 0 t2::: 11008688374415360
i::: 7 t::: 2000
t1::: 8589934594100 t2::: 9222668349412999168
i::: 4 t::: 2129
i=====8 n=====8
t1::: 2000 t2::: 9222668349412999168
i::: 5 t::: 2115
t1::: 9083855833169 t2::: 8594672046007986432
i::: 2 t::: 8595446443790043232
t1::: 9019431323715 t2::: 8594672046007986432
i::: 3 t::: 8595446443790043225
t1::: 9178345113696 t2::: 8594672048301670398
i::: 0 t::: -8589932230
9851160328407354

1 个答案:

答案 0 :(得分:0)

您需要使用printf()正确的格式说明符。请检查以下代码。

对于long int,说明符为%ld

#include<stdio.h>

long int a[1000];
long int cache[1000];
int n;


long int max(long int a,long int b)
{
    if(a>b)
        return a;
    else
    return b;
}


long int solve(int i)
{
    //printf("%d\n",i);
    long int t1,t2,t;
    if(i>(n-1)){
            printf("i=====%d n=====%d\n",i,n);
        return 0;
    }
     if(cache[i]!=-1)
        return cache[i];

    t1=solve(i+2);
    t2=solve(i+3);
    printf("t1::: %ld t2::: %ld\n", t1, t2);
    t = max(t1,t2)+a[i];
    cache[i] = t;
    printf("i::: %d t::: %ld\n", i, t);
    return t;
}

int main()
{
    int t,i;
    long int answer;
    scanf("%d",&t);
    while(t--)
    {
        scanf(" %d", &n);

       for(i=0;i<n;i++)
       {
            a[i] = 0;
            cache[i] = -1;
            scanf(" %ld", &a[i]);
        }
        answer = solve(0);
        printf("%ld\n",answer);
    }
}