0

我正在尝试编写一个代码,通过以下公式计算带有尾递归的 intiger 的双阶乘: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;
}

由于某种原因,我收到以下错误: 错误

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

4

2 回答 2

0

尽量保持 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
}
于 2020-04-14T16:05:25.417 回答
0

尝试只保留 n==0 条件来结束您的功能。因为在这两个函数中你只需将 n 减 1,它必须通过 0,这就是它停止的地方。

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

于 2020-04-12T17:08:17.947 回答