用递归调用编程1+2+3
时间: 2024-01-01 16:05:37 浏览: 29
以下是使用递归调用编程1+2+3的例子:
```cpp
#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
int main() {
int n = 3;
cout << "1+2+3=" << sum(n) << endl; // 输出:1+2+3=6
return 0;
}
```
相关问题
用递归调用编程1+2+3+.....+100的值
以下是使用递归调用编程1+2+3+...+100的值的代码:
```cpp
#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
int main() {
int n = 100;
cout << "1+2+3+...+" << n << "=" << sum(n) << endl;
return 0;
}
```
输出结果为:
```
1+2+3+...+100=5050
```
C语言编程用函数的递归调用编程,计算1!+2!+3!…+10!
好的,对于您的问题,我可以提供以下的 C 语言编程代码:
```c
#include <stdio.h>
int factorial(int num) {
if (num == 1) {
return 1;
}
return num * factorial(num - 1);
}
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d! = %d\n", i, factorial(i));
}
return 0;
}
```
该程序中,通过定义递归函数 `factorial`,来计算输入的数字的阶乘。在 main 函数中,通过调用该函数来打印出 1! 到 10! 的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)