【发布时间】:2014-06-05 06:57:48
【问题描述】:
我正在编写一个程序来计算一个数字的阶乘。我正在使用递归来解决这个问题。我遇到的问题是,一旦我达到 13 号,由于 INT 的限制,它会抛出垃圾号。我想要做的是实现一种在错误发生时捕获错误的方法(没有硬线在 x=13 它必须停止,而是通过输出)。这是我的尝试:
#include <stdio.h>
int factorial( int n)
{
printf("Processing factorial( %d )\n", n);
if (n <= 1)
{
printf("Reached base case, returning...\n");
return 1;
}
else
{
int counter = n * factorial(n-1); //Recursion to multiply the lesser numbers
printf("Receiving results of factorial( %d ) = %d * %d! = %d\n", n, n, (n-1), counter);
if( counter/n != factorial(n-2) ) //my attempt at catching the wrong output
{
printf("This factorial is too high for this program ");
return factorial(n-1);
}
return counter;
printf("Doing recursion by calling factorial (%d -1)\n", n);
}
}
int main()
{
factorial(15);
}
问题在于程序现在永远不会终止。它不断循环并向我抛出随机结果。
由于我无法回答自己的问题,我将使用我的解决方案进行编辑:
int jFactorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
int counter = n *jFactorial(n-1);
return counter;
}
}
void check( int n)
{
int x = 1;
for(x = 1; x < n+1; x++)
{
int result = jFactorial(x);
int prev = jFactorial(x-1);
if (((result/x) != prev) || result == 0 )
{
printf("The number %d makes function overflow \n", x);
}
else
{
printf("Result for %d is %d \n", x, result);
}
}
}
【问题讨论】:
-
为什么
counter / n永远等于factorial(n-2)?别介意添加一个额外的递归案例有点问题,你的数学是错误的。 -
@hobbs 我正在尝试检查阶乘(N)/N 是否不等于前一个数字的阶乘,因为这会告诉我输出是否正确。
-
是的,我明白了。
-
“前一个号码”不是
factorial(n-2),而是factorial(n-1)。 -
我认为您知道,与简单地计算 2..n 的乘积相比,递归是计算阶乘的不好方法。