c - 逻辑哪里错了?

标签 c algorithm

我编写了一个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.

Source

关于c - 逻辑哪里错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772608/

相关文章:

c - 多进程程序的执行时间(linux)

c++ - 在c中的函数内部定义一个函数

c - 限制进程对管道的访问 (Windows)

algorithm - Prolog程序,这个程序应该做什么?

java - 递归函数的常量变量值

c++ - C 风格字符串和 c++ std::string 的函数

c - 为什么我的代码没有超出范围错误?

algorithm - 如何使用组改进暴力破解算法?

java - 用于计算距离的修剪集合

java - 为什么如果我直接添加答案,我的列表函数在这个问题中不起作用,但如果我创建列表的副本则起作用