递归fun(n-1)+2
时间: 2024-06-03 12:08:42 浏览: 12
对于这个递归函数,我们需要知道参数n的具体值才能确定它的返回值。
假设n=1,那么递归函数的调用就变成了fun(0),此时递归函数会直接返回2。
假设n=2,那么递归函数的调用就变成了fun(1),根据上面的结论,fun(1)的返回值为2,所以fun(2)的返回值为4。
假设n=3,那么递归函数的调用就变成了fun(2),根据上面的结论,fun(2)的返回值为4,所以fun(3)的返回值为8。
以此类推,可以得到当n=k时,递归函数fun(n)的返回值为2的k-1次方。
因此,递归函数fun(n-1) 2的返回值为2的n-2次方。
相关问题
递归求1+2+...+n的和
以下是Java和C语言两种递归求1+2+...+n的和的例子:
Java代码实现:
```java
public static int sum(int n) {
if (n == 1) {
return 1;
}
return n + sum(n - 1);
}
// 测试
int n = 10;
int result = sum(n);
System.out.println("1+2+...+" + n + "的和为:" + result);
```
C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
int fun(int m);
int main() {
int n, sum = 0;
printf("Please enter a number:");
scanf("%d", &n);
if (n <= 0) {
printf("Enter error");
exit(0);
}
sum = fun(n);
printf("1+2+...+%d的和为:%d\n", n, sum);
return 0;
}
int fun(int m) {
if (m == 1) {
return 1;
}
return m + fun(m - 1);
}
```
用C语言编程,使用递归方法编写递归函数fun(),其功能是计算S=(1+1/2)+(1/3+1/4)+…+(1/2n-1+1/2n)
```c
#include <stdio.h>
double fun(int n) {
if (n == 1) {
return 1.5;
} else {
return fun(n - 1) + 1.0 / (2 * n - 1) + 1.0 / (2 * n);
}
}
int main() {
int n;
double s;
printf("请输入一个大于1但不大于100的整数n:");
scanf("%d", &n);
s = fun(n);
printf("S的值为:%lf\n", s);
return 0;
}
```
--相关问题--:
1. 什么是递归函数?
2. 递归函数有哪些应用场景?
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](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)