C语言编程题:用递归的方式求年龄问题
时间: 2024-03-18 11:40:07 浏览: 27
好的,这里是使用递归的方式求年龄问题的 C 语言示例代码:
```c
#include <stdio.h>
#include <time.h>
int calculate_age(int birth_year)
{
int current_year = localtime(&time(NULL))->tm_year + 1900;
if (current_year <= birth_year) {
return 0;
} else {
int age = current_year - birth_year;
return age + calculate_age(birth_year + 1);
}
}
// 示例
int main()
{
int age = calculate_age(1990);
printf("Age is %d\n", age); // 输出当前年份减去出生年份的总和,即 2021 - 1990 = 31
return 0;
}
```
这个 C 语言的递归算法与 Python 的示例代码类似,只不过获取当前年份的方式略有不同。需要注意的是,这个算法的递归深度可能会很大,因此可能会有性能问题。如果你需要计算大量人的年龄,可以考虑改用非递归的迭代方式。
相关问题
c语言:用递归算法求斐波那契
斐波那契数列是指:1、1、2、3、5、8、13、21、34、……,即第n个数等于其前两个数之和。
递归算法可以很方便地解决这个问题:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n;
printf("请输入要求的斐波那契数列的项数:");
scanf("%d", &n);
printf("斐波那契数列的前%d项为:", n);
for (int i = 1; i <= n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
```
在这个程序中,`fibonacci`函数使用递归算法来计算斐波那契数列,如果n为1或2,则返回1,否则返回前两项的和。主函数中,先读入要求的项数n,然后使用循环依次输出前n项的值。
C语言:用递归算法求斐波那契
斐波那契数列是指:1、1、2、3、5、8、13、21、34、……,即第n个数等于其前两个数之和。
递归算法可以很方便地解决这个问题:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n;
printf("请输入要求的斐波那契数列的项数:");
scanf("%d", &n);
printf("斐波那契数列的前%d项为:", n);
for (int i = 1; i <= n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
```
在这个程序中,`fibonacci`函数使用递归算法来计算斐波那契数列,如果n为1或2,则返回1,否则返回前两项的和。主函数中,先读入要求的项数n,然后使用循环依次输出前n项的值。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)