【问题标题】:Factorial with recursion带递归的阶乘
【发布时间】:2019-07-24 14:11:58
【问题描述】:
#include <stdio.h>
long int fact(int n);

int main()
{
    int n;
    printf("Enter number\n");
    scanf("%d",&n);
  printf("Factorial:%ld\n",fact(n));
    return 0;
}


long int fact(int n)
 {
   if(n!=1)
   return n*fact(n-1);

    }

我正在尝试通过递归获得数字的阶乘。但我每次都得到 0 作为结果。这段代码有什么问题?

【问题讨论】:

  • n 为 1 时返回什么?
  • 记得在编译时打开所有警告。如果有警告,想想它们为什么会出现。
  • @FedericoklezCulloca 问题是几个月前问过同样的问题,同样的问题和同样的解决方案。
  • @Gox 链接帖子中的问题是不同语言的完全独立问题。两者之间没有任何相似之处。

标签: c recursion factorial


【解决方案1】:
long int fact(int n)
{
    return n==1? 1 : n*fact(n-1);
}

【讨论】:

  • n 应该是unsigned,你不觉得吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 2015-04-19
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多