设计递归函数,打印100以内的奇数
时间: 2023-06-02 14:01:43 浏览: 55
这里是一个Python的例子:
```python
def print_odd(n):
if n <= 0:
return
if n % 2 == 1:
print(n, end=' ')
print_odd(n-1)
print_odd(99)
```
输出:
```
99 97 95 93 91 89 87 85 83 81 79 77 75 73 71 69 67 65 63 61 59 57 55 53 51 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1
```
相关问题
利用递归函数输出100以内数字累加和
可以使用递归函数来实现100以内数字累加和,具体代码如下:
```python
def sum_recursive(n):
if n == 1:
return 1
else:
return n + sum_recursive(n-1)
print(sum_recursive(100))
```
首先定义一个递归函数 `sum_recursive`,它接收一个参数 `n` 表示累加的最大值。
当 `n` 等于1时,递归结束,返回1。
如果 `n` 大于1,递归调用 `sum_recursive` 函数,并将参数设置为 `n-1`,然后将 `n` 和 `sum_recursive(n-1)` 的结果相加并返回。
最后调用 `sum_recursive(100)` 函数得到100以内数字的累加和,并将结果打印出来。
js 递归函数打印杨辉三角
好的,以下是用 JavaScript 编写的递归函数打印杨辉三角的代码:
```javascript
function yanghui(n) {
if (n === 1) {
return [1];
} else {
const last = yanghui(n - 1);
const current = [1];
for (let i = 1; i < n - 1; i++) {
current[i] = last[i - 1] + last[i];
}
current.push(1);
console.log(current.join(' '));
return current;
}
}
function printYanghui(n) {
for (let i = 1; i <= n; i++) {
yanghui(i);
}
}
printYanghui(5);
```
输出结果如下:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
注:以上代码中的 `printYanghui` 函数调用了 `yanghui` 函数,后者返回一个数组并打印出该数组中的元素。`yanghui` 函数通过递归实现了杨辉三角的生成。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)