开发者

where is the logic wrong?

开发者 https://www.devze.com 2023-02-28 16:14 出处:网络
i wrote a memoized code for computing factorial of a number in C . But on giving the input as n=3 it gives the output as 6! = 开发者_如何学运维134513904 .Can someone please explain what is going wrong

i wrote a memoized code for computing factorial of a number in C . But on giving the input as n=3 it gives the output as 6! = 开发者_如何学运维134513904 .Can someone please explain what is going wrong?

int fact(int n)
{
int temp;
static int lookup_table[100];
if(lookup_table[n])
    return lookup_table[n]; 
else if(n == 0 )
{
    lookup_table[0]= 1;
    return 1;
}   
else
{
    temp = n * fact(n-1);
    lookup_table[n] = temp;
    return temp;
}

}


One problem could be that you don't ever initialize your table, so it is filled with whatever happens to be in memory.

Edit: Ah, it seems I'm wrong and that the behavior is well defined:

If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.

Source


Your printf (from a comment) doesn't have the correct number of arguments, and therefore prints a garbage value:

printf("\n%d! = %d\n",result);

Contrary to what others have said, the array doesn't have to be initialized explicitly, as the C standard says:

If an object that has automatic storage duration is not initialized explicitly,its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer
  • if it has arithmetic type, it is initialized to (positive orunsigned) zero
  • if it is an aggregate, every member is initialized (recursively) according to these rules
  • if it is a union, the first named member is initialized (recursively) according to these rules.

However, it's good pratice to initialize explicitly in order to make your intentions clear.


Like I suspected, problem is with the printf and not the function.

0

精彩评论

暂无评论...
验证码 换一张
取 消