我编写了一个memoized
代码,用于在 C 中计算数字的阶乘。但是当输入为 n=3
时,它的输出为 6! = 134513904
。有人可以解释一下出了什么问题吗?
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;
}
}
最佳答案
一个问题可能是您从未初始化表,因此它填充了内存中的任何内容。
编辑:啊,看来我错了,而且行为定义良好:
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.
关于c - 逻辑哪里错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772608/