C语言 用递归实现阶乘

执行结果截图:

输入整数5,最后输出整数5的阶乘结果120,截图中展示了函数fact() 进行递归运算的过程。

如果输入整数5,那么函数fact()总共被调用了6次,其中1次是用于判断是否满足递归结束条件。

 

 代码:

#include <stdio.h>

long fact(int num);
int count;

long fact(int num)
{
long result;
printf("fact(%d) loading... \nnum:%d result: %ld\n", num, num, result);
extern int count;

if(num > 0)
{
printf("Before the next level recursion of fact()... result: %ld\n", result);

/* 这行代码是对函数fact()的递归调用,是含递归运算的代码行;
* 这行代码会先执行fact(num - 1),也就是对fact进行递归式的调用,
* 也就是暂时不会执行该递归代码行其他的运算,
* 直到递归的结束条件num > 0满足后,
* 才开始从嵌套的最里层将返回值result返回给外一层的fact()
*/
result = num * fact(num - 1);
count++;
printf("Operating 'result = %d * result of fact(%d)' ...\nresult:%ld\n", num, count-1, result);
}
else
{
printf("\nNow num:%d which is not > 0\n", num);
printf("So no more further recursion of fact()...\n");
result = 1;
printf("set value of result to 1\n\n");
}

printf("fact(%d) returning result to upper level...\n", count);
return result;
}

int main(void)
{
int num;

printf("请输入一个正整数:");
scanf("%d", &num);
printf("Inputted num:%d\n", num);
printf("\n%d的阶乘是:%ld\n", num, fact(num));

return 0;
}
posted @   JohnnyH  阅读(668)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示