栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言入门(十九)>>>函数(四)- 函数和递归

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言入门(十九)>>>函数(四)- 函数和递归

文章目录
    • 递归与迭代
      • 练习三:
        • 递归
      • 练习四:
        • 递归
        • 循环

递归与迭代 练习三:

求n的阶乘。(不考虑溢出)

#include 
#include 

int Facl(int n)
{
	int i = 0;
	int ret = 1;
	for (i = 1; i <= n; i++)
	{
		ret *= i;
	}
	return ret;
}
int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Facl(n);
	printf("%dn", ret);
	return 0;
}
递归
#include 
#include 

int Facl2(int n)
{
	if (n <= 1)
		return 1;
	else
		return n * Facl2(n - 1);
}

int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Facl2(n);
	printf("%dn", ret);
	return 0;
}
练习四:

求第n个斐波那契数。(不考虑溢出)

递归
#include 
#include 

int Fib(int n)
{
	if (n <= 2)
		return 1;
	else
		return Fib(n - 1) + Fib(n - 2);
}

//斐波那契数列
//1 1 2 3 5 8 13 21 34 55
int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	//TDD - 测试驱动开发
	ret = Fib(n);
	printf("ret = %dn", ret);
	return 0;
}
循环
#include 
#include 

int Fib(int n)
{
	int a = 1;
	int b = 1;
	int c = 1;

	while (n > 2)
	{
		c = a + b;
		a = b;
		b = c;
		n--;
	}
	return c;
}
int main()
{
	int n = 0;
	int ret = 0;
	scanf("%d", &n);
	ret = Fib(n);
	printf("ret = %dn", ret);
	return 0;
}

仅供学习参考使用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968764.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号