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

时间:2019-10-16 12:29:13

标签: c factorial

当我运行该程序时,它也会给出答案,但是当选择选项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;
}

3 个答案:

答案 0 :(得分:1)

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

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

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

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

        // Calculate
        temp = num;
        res = 1;
        while (num)
        {
          res = res * num;
          num = num - 1;
        }

        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');

    return 0;
}

答案 1 :(得分:1)

“ main()”的递归调用是否代表程序重置? 如果是这样,为什么不使用无限循环来检查输入,然后在体内进行析因计算,输出(如打印等),并在不再需要某个输入时结束程序。 我相信这应该可以解决问题:

{"id":"Ho1u8aA2p8jGuzEIZq8n","data":{"spa_id":"0","os":"10.14.6","name":"Spa_Name","activity":"0","spa_email":"info@spa.com","serial":"C07XMRXWJYVW","nation":"Italy","spa_address":"Apliu Street 54, Hong Kong","ip_address":"192.168.2.1","global_unit_id":"0","city":"Perugia","branch":"Main","spa_unit_nr":"1","uid":"dev","spa_website":"www.spaname.com","continent":"Europe","spa_phone":"+852 3847569"}}

答案 2 :(得分:0)

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

=>删除“ main();”