我正在编写代码来解决 Rod Cut 问题,但在运行时我一直收到 Segmentation Fault 提示。我尝试使用 gdb 对此进行调试,它显示了 recRodCut 函数的问题。谁能帮我找到问题所在?
#include <stdio.h>
int recRodCut(int* arr, int n)
{
int res;
int i;
if(n==0)
{
return 0;
}
for( i = 0; i< n ; i++)
{
res = max(recRodCut(arr,n) , arr[i]+recRodCut(arr,n-i));
}
return res;
}
int max(int a, int b)
{
return (a<b)?a:b;
}
int main()
{
int value[] = {0,1,5,8,9,10,17,17,20,24,30};
int result = recRodCut(value, 4);
printf("The value is %d \n", result);
}
最佳答案
我在这里没有看到段错误,但我看到了一个未终止的递归,它最终导致堆栈溢出。
考虑如何调用 recRodCut()
:
recRodCut(value, 4);
// i = 0, first iteration:
res = max(recRodCut(value, 4), value[0]+recRodCut(value, 4-0));
如您所见,您总是使用相同的参数调用 recRodCut。这意味着它永远不会命中 if(n==0)
并提前退出。
顺便说一句,你的 max()
函数实际上是一个 min()
函数:)
关于c - 如何删除此代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31922710/