#include <stdio.h>
#include <stdlib.h>
int factorial (int b);
int main (void) {
int a;
scanf("%d", &a);
int fac = factorial(a);
printf("Your final result is: %i", fac);
}
int factorial (int b) {
if (b == 0) {
return 0;
}
else if (b == 1) {
return 1;
}
return b * factorial(b - 1);
}
在 cs50 的 Tideman 学习编程之后,我尝试学习递归,但程序永远不会结束。我正在使用 cs50 IDE,不知何故,它的库中的 cs50 函数(例如 get_int())也不起作用?我很困惑。无论如何,如果你能看到代码中任何明显的错误,我可以修复 lmk!非常感谢
我建议添加一些简单的测试并返回一个指示错误情况的值。如果不进行检查,您的代码将在整数溢出时调用未定义的行为
进行这些更改后,它将正常工作。
int factorial (int b)
{
if(b < 0) return -1;
else if (b == 0) return 0;
else if (b == 1) return 1;
int result = factorial(b - 1);
if(INT_MAX / result >= b) return b * result;
else return -1;
}
int main(void)
{
for(int x = -1; x < 100; x++)
{
printf("%d! = %d\n", x, factorial(x));
}
}
https://godbolt.org/z/dsjb8bbfT
顺便说一句,整数查找表就足够了:
int fact(int b)
{
static const int results[] = {0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600};
if(b < 0 || b >= sizeof(results) / sizeof(results[0])) return -1;
return results[b];
}