我的程序如下:为什么我的递归函数seg在C中出错?
#include <stdio.h>
int collatz(int seed, int count) {
int next = 0;
if (seed % 2 == 0) {
next = seed/2;
} else {
next = 3 * seed + 1;
}
count++;
if (next == 1) {
return count;
} else {
return collatz(next, count);
}
}
int main() {
int max = 0;
int index = 0;
int i;
for (i=1; i<1000000; i++) {
int current = collatz(i, 1);
if (current > max) {
max = current;
index = i;
}
}
printf("%i\n", index);
return 0;
}
我明白,递归通常只到一定的深度。但据我所知,我已经实现了尾部递归,它应该能够阻止seg故障。如果我将我设置为100,000,程序运行将导致我相信底层算法是正确的。但是一百万,我得到:
分段故障:11
我在做什么错?
什么时候它segfault?你的调试器说什么? –
因为你用深度递归炸毁堆栈? –
这不是尾递归,除非编译器将其转换为尾递归。在C中,你必须使用'while(next!= 1)'而不是在最后调用'collatz'。 –