仅使用主函数查找数字阶乘的程序

问题描述 投票:-1回答:3

[当我运行该程序时,它也会给出答案,但是当选择选项n时,它将再次要求输入选项进行检查并提供良好的解决方案

#include<stdio.h>
int main()
{
    char ch;
    static int count = 0;
    static int num;
    static unsigned long long int res;
    static int temp;

    if (count == 0)
    {
        printf("Enter the value of Number:");
        scanf("%d", &num);
        if (num < 0)
        {
            printf("Invalid input.");
            return 0;
        }
        temp = num;
        res = 1;
        count++;

        do {
            main();
            printf("Factorial of %d is\t:%llu\n", temp, res);
            printf("Do you want to continue y/n :");
            scanf("\n%c", &ch);

        } while (ch == 'y' || ch == 'Y');
    }

    //Logic for recursive factorial function
    if (num > 0)
    {
        res = res * num;
        num = num - 1;
        main();
    }
    else
    {
        count = 0;
    }
    return 1;
}
c factorial
3个回答
1
投票

main的递归调用绝对是“不行”。绝对不要那样做。相反,您只需在收到输入后就将阶乘的计算放进去。

我不会将其称为一个好的解决方案,但是下面的代码与您自己的代码很接近,并且避免了main的递归调用。


0
投票

它再次询问,因为您正在同时递归地调用main函数。不知道您要对此递归调用做什么,但是可以确定您应该删除此行。


0
投票

您能否对您想做的事情进行更广泛的解释?这看起来是查找阶乘的怪异实现。

© www.soinside.com 2019 - 2024. All rights reserved.