C-整数除以零的尾递归双因子分解

  • 本文关键字:分解 尾递归 整数 c
  • 更新时间 :
  • 英文 :


我正试图编写一段代码,通过以下公式计算具有尾部递归的整数的双阶乘:DoubleFactorial。

这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// Test cases: 5!! = 15; 10!! = 3840;
long long Factorial(int n) {
if (n < 0) // assignment assumption
return 0;
if (n == 0) // stopping condition
return 1;
return n * Factorial(n - 1); // non-tail recursive step
}
int tail_recursion_double_factorial(int n, int accumulator) {
if (n < 0) // assignment assumption
return 0;
if (n == 0) // stopping condition
return accumulator;
if (n == 1) // stopping condition -- return the most updated counter
return accumulator;
return Factorial(n) / tail_recursion_double_factorial(n - 1, n*accumulator); // TAIL RECURSIVE step -- using formula for double factorial
}
int main() {
int n;
long long res; //res doesn't have to be of type int.
printf("Please enter a number:n");
scanf("%d", &n);
res = tail_recursion_double_factorial(n,1); // assigning the recursive call to a variable
printf("%d!! = %ld", n, res); // NOTE: IF YOU CHANGE THE TYPE OF RES - CHANGE THE SPECIAL CHARACTHER SPECIFIER (%) ACCORDINGLY
return 0;
}

由于某些原因,我得到以下错误:错误

我尝试了所有的方法,但不确定是什么导致了这个错误——我看不出被零除的问题可能发生在哪里。

尽量保持n=0条件来结束函数。因为在这两个函数中,你只需将n减少1,它就必须通过0,这就是它将停止的地方。

您还可以检查输入n是否为有效的>1个数字的

尝试保持n-1的递归而不乘以n

int tail_recursion_double_factorial(int n, int accumulator) {
if (n < 0) // assignment assumption
return 0;
if (n == 0) // stopping condition
return accumulator;
if (n == 1) // stopping condition -- return the most updated counter
return accumulator;
return Factorial(n) / tail_recursion_double_factorial(n - 1, accumulator); // TAIL RECURSIVE step -- using formula for double factorial
}

最新更新