编写递归函数:int sum(int n); 求1+2+3+...+n的值,并用主函数测试之。
时间: 2023-11-17 09:04:23 浏览: 41
以下是递归函数的实现:
```c++
#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n-1);
}
}
int main() {
int n;
cout << "请输入一个整数n:" << endl;
cin >> n;
cout << "1+2+3+...+" << n << "=" << sum(n) << endl;
return 0;
}
```
递归函数的思路是:当n为1时,返回1;否则,返回n加上sum(n-1)的值。在主函数中,用户输入一个整数n,然后调用sum函数来计算1+2+3+...+n的值,并输出结果。
相关问题
编写递归函数:int sum(int n); 求1+2+3+...+n的值,并用主函数测试之
以下是递归函数 `sum` 的实现:
```c++
int sum(int n) {
if(n == 1) {
return 1;
}
else {
return n + sum(n-1);
}
}
```
该函数的思路是:当 `n` 为 1 时,返回 1;否则返回 `n` 与 `sum(n-1)` 的和。这样就可以累加 1 到 `n` 的值了。
以下是主函数的测试代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入 n:" << endl;
cin >> n;
cout << "1+2+3+...+" << n << "=" << sum(n) << endl;
return 0;
}
```
运行该程序,可以输入一个正整数 `n`,然后程序会输出 1 到 `n` 的和。
编写递归函数:int sum(int n); 求1+2+3+...+n的值,并用主函数测试之c语言
下面是递归函数 `sum` 的实现:
```c
#include <stdio.h>
int sum(int n) {
if (n == 1) { // 递归终止条件
return 1;
} else {
return n + sum(n-1); // 递归调用
}
}
int main() {
int n = 10;
int result = sum(n);
printf("1+2+3+...+%d=%d\n", n, result);
return 0;
}
```
递归函数 `sum` 的思路是,当 `n` 等于 1 时,直接返回 1;否则,计算 `n` 加上 `sum(n-1)` 的结果,即可得到 1+2+3+...+n 的值。
在主函数中,我们测试了 `sum(10)` 的值,输出结果为:
```
1+2+3+...+10=55
```
相关推荐
![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_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)
![](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)