【问题标题】:Why my simple C code to calculate factorial not working [closed]为什么我计算阶乘的简单 C 代码不起作用[关闭]
【发布时间】:2020-11-10 22:59:38
【问题描述】:

如果我输入零或负值,以下代码将正确返回。但是,如果我输入任何正值,它什么都不做。
有人可以解释为什么吗?我的期望是,它应该返回正数的阶乘。

#include<stdio.h>

int functionfact(int);

void main()
{
    int x,fact;

    printf("Input an integer value:\n");
    scanf("%d",&x);

    if (x<0)
        printf("Please enter positive value!!");

    else if (x==0)
        printf ("The factorial of 0 is 1");

    else
    {
       fact=functionfact(x);
       printf("The factorial of %d is %d",x,fact);
    }
}

int functionfact(int n)
{
    return(n*functionfact(n-1));
}

【问题讨论】:

标签: c factorial


【解决方案1】:

我赞成 Kalbi 的提议,但我会把它写成:

int functionfact(int n)
{
    if (n > 0) {
        return n * functionfact(n-1);
    } else {
        return 1;
    }
}

让我们面对现实吧:这个问题是由正在学习递归基础知识的初学者提出的。最好是先对如何处理这种编程有一个完整的了解(因为我们之前都在苦苦挣扎,递归并不容易),然后再做一些典型的 C oneliners。

【讨论】:

    【解决方案2】:

    正如 Eric 指出的那样,函数现在无法停止。

    如果你只是将功能更改为它应该可以工作

    int functionfact(int n)
    {
        return n > 0 ? (n*functionfact(n-1)) : 1;
    }
    

    【讨论】:

      【解决方案3】:

      亲爱的你好!

      函数functionfact 没有任何终止条件。你可以试试这个……

      int functionfact(int n)
          {
              if(n>1)
              return(n*functionfact(n-1));
          }
      

      希望你能得到答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多