目录

5. 函数的嵌套调用和链式访问
函数和函数之间可以根据实际的需求进行组合的,也就是互相调用的。
5.1嵌套调用
#include <stdio.h>
void new_line()
{
printf("hehe\n");
}
void three_line()
{
int i = 0;
for(i=0; i<3; i++)
{
new_line();
}
}
int main()
{
three_line();
return 0;
}
5.2 链式访问
#include <stdio.h>
#include <string.h>
int main()
{
char arr[20] = "hello";
int ret = strlen(strcat(arr,"world"));//这里是10
printf("%d\n", ret);
return 0;
}
#include <stdio.h>
int main()
{
printf("%d", printf("%d", printf("%d", 43)));
//结果是啥?
//注:printf函数的返回值是打印在屏幕上字符的个数
return 0;
//这里打印出来的是4321
6. 函数的声明和定义
6.1 函数声明
6.2 函数定义
7. 函数递归👑
7.1 什么是递归?
7.2 递归的两个必要条件
7.2.1 练习1
接受一个整型值(无符号),按照顺序打印它的每一位。
例如:
输入:1234,输出 1 2 3 4
#include <stdio.h>
void print(int n)
{
if(n>9)
{
print(n/10);
}
printf("%d ", n%10);
}
int main()
{
int num = 1234;
print(num);
return 0;
}
7.2.2 练习2
题目:
编写函数不允许创建临时变量,求字符串的长度。
#incude <stdio.h>
int Strlen(const char*str)
{
if(*str == '\0')
return 0;
else
return 1+Strlen(str+1);
}
int main()
{
char *p = "abcdef";
int len = Strlen(p);
printf("%d\n", len);
return 0;
}
7.3 递归与迭代
7.3.1 练习3
求n的阶乘。(不考虑溢出)
int factorial(int n)
{
if(n <= 1)
return 1;
else
return n * factorial(n-1);
}
7.3.2 练习4
求第n个斐波那契数。(不考虑溢出)
//递归
//int Fib(int n)
//{
// if (n <= 2)
// return 1;
// else
// return Fib(n - 1) + Fib(n - 2);
//}
//
//迭代
int Fib(int n)
{
int a = 1;
int b = 1;
int c = 1;
while (n >= 3)
{
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
//求斐波那契数
int main()
{
int n = 0;
scanf("%d", &n);
n = Fib(n);
printf("%d\n", n);
return 0;
}
提示: